#archived-code-general
1 messages · Page 134 of 1
You wouldn't make health a part of the interface. You would create something like IDamageable
And then handle the OnDamage function uniquely
Ah ok
You can ignore any parameter you're passing, in the switch implementation
Makes me think of that "adding helicopters in game dev" meme
Ah interesting
Just thought id ask
So like for an enemy OnDamage would have an int amount
i usually wind up making a Damage struct/class
it might contain a list of kinds of damage
or just literally be
public struct Damage {
public float amount;
}
if I'm not quite sure what I'll need yet
YAGNI -- You Ain't Gonna Need It -- suggests you just make it a float until we change it later
but it's not much extra work to just use the struct from the start
This, so if you ever need to add stuff later on, no need to go through all call sites to add a parameter
only problem is capturing bunch of modifiers later
Why does prefab that I Instantiate stay in the Scene, when Game is finished?
or is it always so?
how do you instantiate it
So if OnDamage(int amount) is in the interface does that mean everything that uses IDamage need an int for how much damage?
at runtime?
yes
interface is a contract
TMP_Text newTextComponent = Instantiate(textComponentPrefab, textComponentsHolder.transform);
"class is obligated to have this method verbatim"
where do you do this
Cause a switch like that wouldnt need the damage amount since theres no health
private int textComponentIndex
{
get => m_textComponentIndex;
set
{
while (_textComponents.Count <= value)
{
TMP_Text newTextComponent = Instantiate(textComponentPrefab, textComponentsHolder.transform);
_textComponents.Add(newTextComponent);
}
m_textComponentIndex = value;
_textComponent = _textComponents[value];
}
}
but an enemy does
then just dont use the parameter
if this happens in the editor, then they will stick around
in the editor?
you're free to ignore parameters
how to avoid it?
looks like something is calling it outside of playmode
Now, there is another option here: separate "damage" from "activation"
everything in my script is being called outside of playmode actually
@marble halo you can drop a parameter by using _
You might do that if you have many different kinds of things you "activate"
ah ok
so maybe you have elecrtic arrows that do electric things
but!
i like the idea of keeping it all together. so electric arrows do electric damage and turn on electric objects
Hell, you can even make interfaces "inherit" from others so their methods accumulate
now there is harmony.
do you have a guard with EditorApplication.playModeStateChanged ?
hey, game idea is forming here...
wait, this is just bioshock
zap
I do not use it if that's what you mean
what do you mean?
I have just written normal script as I always do
nothing special with Aplications in it
you are writing scripts for edit mode
completely different semantics
what does it mean?
I am writing my script as usually
there are 2 modes, Edit mode and Play mode
for example if you instantiate a prefab in play mode with Instantiate it will work as you expect
if you do the same in editor you are creating a broken/incorrect instance
because while in edit mode the correct way is to use PrefabUtility.Instantiate...
there are a lot of cases like that
lots of things to keep track of
Destroy/DestroyImmidiate for example
by default it's done in Play mode, right?
what default
i asked you if you do it in play mode you said everything is outside of it
play mode is a state of unity editor
when you press the play button it switches to it
oh, you mean that
if youre doing editor tooling you have to use editor approach for things
and cleanly separate play/edit behaviors
if you mix them with ExecuteAlways for example
Unity uses Play mode by default, right?
i dont understand the question
default in what context
wait, actually that was dumb question
ok, so Play and Edit behaviours are seperated by default
you can edit during play, however it won't stay after play is finished
whatever edits you do during play, it only affects the play session
everything goes back to what it was before you hit play
it stays though
that means its created outside of play mode
well it might depend on what you're editing then
(i'm new here btw. asking questions mostly. lol)
yes, my issue is that intantiated objects stay in Edit
for example you have some Awake/OnEnable in a class with [ExecuteAlways]
how can it even happen?
I don't
📃 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.
you pause play (or not), then "tab out" to edit tab, and do whatever you want.
[ExecuteAlways]
[SelectionBase]
public class Selectable
I see
how to avoid it?
i dont think you can avoid it here
but you can modify your code accordingly
also i dont understand why you hid virtual methods
instead of overriding them
that should most likely break the whole thing
you mean Awake and Start?
yes
i'm not sure how override vs. new behave with respect to unity messages
why should I override them?
override doesn't mean that both methods get called...
if event system operates on selectable directly, your new methods should not be called at all
if you call base();
ah, fair.
pacman game, player collider, ghost collider
which one of the two should i mark for "is trigger"?
i know i can do in any of the two, but is there a best design?
Guys why am I getting this NullReferenceException here?
{
stairSpawner.SpawnedStair += IncreaseStairCount;
}
{
stairSpawner = FindObjectOfType<StairSpawner>();
}
no objects of this type
a virtual method called on a base class will invoke the highest override first, a method that hides base method on a subclass will not be called if the base method is called on the base class
OnEnable runs before Start
right, I was just thrown off by how you said "your method would be called as well"
Ah thank you
it runs immediately after Awake, too
Awake and OnEnable are instant; Start is before the next Update
Yeah, so you could move the code from Start to Awake here
Yep that's what I did
Can anyone help me figure out this input system code?
[System.Serializable]
public struct TextIARPair
{
public TMP_Text Text;
public InputActionReference IAR;
}
[SerializeField] List<TextIARPair> _textIARPairList = new List<TextIARPair>();
InputActionRebindingExtensions.RebindingOperation _rebindingOperation;
InputControls _controls;
void Start()
{
_controls = Get<PlayerInput>().Controls;
string rebinds = PlayerPrefs.GetString("rebinds", string.Empty);
if (string.IsNullOrEmpty(rebinds)
return;
_controls.LoadBindingOverridesFromJson(rebinds);
foreach (var pair in _textIARPairList)
pair.Text.text = KeybindToText(pair.IAR);
}
public void Save()
{
string rebinds = _controls.SaveBindingOverridesAsJson();
PlayerPrefs.SetString("rebinds", rebinds);
}
public void StartRebinding(InputActionReference iar)
{
TextIARPair pair = FindPair(iar); // Gets pair from list
_controls.Disable();
_rebindingOperation = iar.action.PerformInteractiveRebinding()
.OnMatchWaitForAnother(0.1f)
.OnComplete(x => RebindComplete(pair))
.Start();
}
void RebindComplete(TextIARPair pair)
{
_rebindingOperation.Dispose();
_controls.Enable();
Save();
}
public void ClearBindings(InputActionReference iar)
{
iar.action.RemoveAllBindingOverrides();
Save();
}```
When I change a keybind it assigns it correctly but when I leave the pause menu I cannot perform any inputs, also if I restart play mode it doesn't seem to save any of the keybinds. A lot of this stuff is going over my head tbh
When I do this I get an empty string back:
string rebinds = _controls.SaveBindingOverridesAsJson();
Debug.Log(rebinds);```
But this returns the new overriden keybind at the same time:
```cs
string KeybindToText(InputActionReference iar)
{
int bindingIndex = iar.action.GetBindingIndexForControl(iar.action.controls[0]);
string path = iar.action.bindings[bindingIndex].effectivePath;
return InputControlPath.ToHumanReadableString(path, InputControlPath.HumanReadableStringOptions.UseShortNames);
}```
So I think there's something wrong with SaveBindingOverridesAsJson() but I'm struggling to think of why
Although considering the fact that the overriden inputs aren't getting detected, the problem is probably there
What's wrong with this code?
// Variables
InputActionRebindingExtensions.RebindingOperation _rebindingOperation;
InputActionReference iar;
// During Binding
_rebindingOperation = iar.action.PerformInteractiveRebinding()
.OnMatchWaitForAnother(0.1f)
.OnComplete(x => RebindComplete())
.Start();
// On Complete
void RebindComplete()
{
_rebindingOperation.Dispose();
}```
The problem must be within here
Ok I found out why the player was unable to move, unrelated problem. But the keybinds still aren't saving
Nor being applied at all
Problem is still within here
Ayy got it working, problem was with the fact that the InputAction I assigned in the inspector was different to the one I actually used for detecting input and saving/loading. I didn't realise they were different :P whoops
Why would you need to mark either as "is trigger"? Are you using OnTriggerEnter on a specific object?
One question, is there a way to like lock the cursor to the middle of the screen/hide it but still be able to interact with world canvas elements such as buttons please?
Locking the cursor doesn't prevent this
when I lock the cursor I can't use the UI
Like, at first with the mouse unlocked I can click and move the scroll rect, but once I lock it I cannot click or move it anymore
I'm having an issue with the Async/Await workflow. Let's say I have methods A(), B(), and C(). Method C() is a async Task that awaits some other Task. within Method A(), there's a loop which calls B() each iteration, and within B(), a loop which calls C() in each iteration. The execution of Method C() stops when it reaches the await statement; however, methods B() and A() each complete their loop statements without waiting for the Task in method C() to be fulfilled.
If I want the await in Method C() to halt the entire chain, does that mean that A() and B() also need to be async methods that are awaited?
For cleanliness purposes, I dislike making every method in the chain an async method because it mostly doesn't ever need to await anything and I find myself adding a lot of "return Task.CompletedTask;" at the end of methods. Is there another way to go about this other than marking every thread that might be awaited downstream without converting them all to async Tasks?
Async programming tends to "infect" the project like this, at some point you either start blocking or possibly do some black magic with a custom scheduler that blocks in a controlled manner to prevent locking a program up (speaking broadly and coming from Rust, not even sure if that second part can be done in C#)
it's turtles all the way down
yes
there is no way to "halt" a normal method
async method is converted to a state machine
its literally a giant switch under the hood
same for enumerators, right?
yes
every vaguely magical C# feature is just a state machine in a trenchcoat
assumed you needed a trigger
did some reading and in the end i don't
however i was left confused as to what occasions require a trigger and what do not use on
you need a trigger when you need a trigger!
i read the manual on it, but still
pacman and ghosts do not interact with each other in what physics are concerned (there is no physics simulation)
it's basically, collision = one of them goes poof
wouldn't marking as trigger make the collision cheaper or something because no physics simulation?
when you want to detect things without collisions
yes, triggers are simpler.
the main draw is that you don't mess with physics.
but isn't a trigger necessarily a collider (with "is trigger" marked)?
you don't run into an autosave point and bounce off
you just walk into the trigger zone
but can't you make do with a collider (without a rigidbody)?
same thing, "OnCollisionEnter" -> save game
yes
didn't realize a collider was going to block stuff unless it had a rigidbody
so no rigidbody necessary to block stuff then?
no idea why i always assumed you needed a rigidbody to block
colliders are colliders
having a rigidbody is necessary to be affected by physics and to receive collision events
One of the two objects must have a rigidbody to receive any physics messages
wait, on "to receive collision events"
can you give me an example of a collider interaction that requires a rigidbody?
well, to start
if you have two objects with colliders, and neither has a rigidbody
collisions don't really matter
they ain't moving
if you manually move them into each other, you won't get collision events
OnCollisionEnter, for example
hmmm now it starts to make sense
Rigid body = something to be controlled by physics, things without it but with colliders are essentially static objects that can be run into
but pacman and the ghosts don't need rigidbodies to be implemented do they?
i mean i'm not going to use any physics simulation to move them around
They can use a kinematic rigidbody
how can i implement the object "touch" or "overlap" detection?
Kinematic rigidbodies are still understood by the physics system
But they aren't affected by physics
you can detect if they overlap by other means, but might as well still use collision events
so i can't actually code "touch" events without rigidbodies in the end?
i mean with the given tools, not having to resort to coding my own
talking about colliders, rigidbodies, triggers etc etc
and the "oncollision" "ontrigger" events
Rigidbodies are required.
Yes u need a rigidbody, otherwise your object isnt really supposed to move and collide
it's funky but something needs a rigidbody, but like that rigidbody can be kinematic
It's fine if you aren't making the player be affected by physics
like, the player doesn't get pushed around
now i'm confused as to why make colliders and rigidbodies separate thigns
although, a kinematic rigidbody also ignores collisions
a collider is the shape
a rigidbody is what makes you into an object that gets pushed around by physics
so the collider is basically the shape of the rigidbody?
because a collider and a rigidbody are 2 entirely separate things
it's the shape of the object
a rigidbody has no shape
Hey there, I'm wondering how I could go about adding a planting mechanic for my game. More specifically, I have a few things I want to try and do.
First, I want to create a box collider that would go around the entire plant model, which is made up of multiple gameobjects. Next, I'd want to apply a material to both the parent model and all of its children.
It's worth considering that if you're using a physics engine for a Pac-Man clone you might be bringing an automatic shotgun to a knife fight
if i have a collider (no rigidbody) setup, and another collider (with rigidbody) touches it, will it stop moving (and be blocked) by the no-rigidbody collider?
best to think of a collider as just a collider
its just a physics shape
you can have 10 colliders representing a single "object"
object in this case is some abstraction, like a mesh
let me see if i'm starting to understand it better
yes. because the rigidbody respects colliders.
yes, you can test this by putting a rigidbody on a cube. Then just put another stretched cube to act as a floor. 2nd cube with no rigidbody
rigidbody treats a group of colliders as a physical object
you can have many colliders under the same rigidbody and they will act as a single physics object
the only slightly annoying part about many colliders is dealing with which one got hit
that is solved through relaying events to the root
if that matters for your game
so an object with a collider and no rigidbody would be better suited to serve as a boundary or a no-physics wall of some kind?
whereas if i mark it as "is trigger" i transform that same objecti with collider but no rigidbody in a penetrable/traversable "area" (instead of a wall) that will send "ontrigger" events?
colliders still participate in physics they just dont move
yea its easily solved, i just dont like having a script on each child object. Maybe its different for me, i got 18 colliders :p
a floor collider doesnt need a rigidbody, it doesnt move
but physx still uses it to compute collisions for rigidbodies
so object+collider (no rb) = "wall"
object+collider (no rb) +isTrigger = "named traversable area"
object+collider+rigidbody = an actual movable object in the physical world
If you want to ignore rigidbodies completely, just cast (sphere/box) yourself. You wouldn't use OnTriggerEvents but rather your own methods.
i'd like to use the stock functions as much as possible, especially to actually learn them
You'd have more control on when to check as well which is a plus
i've published a game (shocking right) using all of that but without understanding 20% of it
what if i have an object+rigidbody with a collider set as "isTrigger"
how would such a monster behave?
kinda, the wording is slightly off. you can still move objects that dont have rigidbodies, but thats just moving the actual transform.position. Rigidbodies allow them to move via forces, have angular rotations, be affected by gravity
Like you can close and open a door without putting a rigidbody on it
ohhhh, the translate vs. force was very insightful
as for the triggers, u can use them however u want really but yea its more so detecting if something entered an area, or just left the area
but how would a rigidbody with a collider marked as trigger work?
a trigger is different, your rigidbody would essentially just fall through the floor
Rigidbodies are mostly for using unity's physics, not primarily a focus (more of a subset) on the collisional aspects, but there is some functionality that it introduces that does help against faster projectiles
do rigidbodies not need colliders in order to collide (to stop, be stopped or physically interact) with other stuff?
if you give your rigidbody a collider AND trigger, you can use the trigger to detect if things are within your trigger area for example. Like if you had items to pickup from the floor, you dont want to calculate the distance between yourself and every item. You would rather have a trigger that can detect if an item entered its bounds
triggers just have a different use
that means two colliders right? one of them being marked as trigger?
yea
so marking a collider as a trigger transforms it into something else entirely i guess?
i mean, it stops being a "collider" since it won't collide with anything anymore?
it's just detect overlaps (ontriggerenter)?
I guess you can word it like that yea. One of the 2 objects still needs a rigidbody though
also 2 triggers cannot collide
actually i remember this being something weird, someone corrected me on it but i forgot what they said
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
If both GameObjects have Collider.isTrigger enabled, no collision happens
the docs say this but i think that refers to an actual Collision instead of OnTriggerXXX
This is wrong. The "colliders overview" page contradicts that
I think it was true at one point...
i remember reading about people complaining about it
ah i once again fell for the misleading wording
i'm pretty sure the page is asserting that no messages get sent
The same applies when both GameObjects do not have a Rigidbody component.
this is true: no trigger messages get sent
english is hard
wait
so it's actually impossible to implement "pacman eats ghosts" without rigidbody, be it with OnCollisionEnter or OnTriggerEnter
since any will require at least one rigidbody?
Yes. If you want collision events, you must have a rigidbody on at least one object
end of story.
Having a rigidbody does not mean that the object is affected by physics
it can be kinematic
kinematic rigidbodies are not affected by forces
you just have to move them with Rigidbody.MovePosition instead of setting the transform's position directly
that's all
that might work, sometimes
the problem is that this moves the object without letting the physics system handle it
it might be ok
but yeah a rigidbody and colliders (and triggers) to implement a "one object goes poof" on "touch"
it's the game snake basically, but with smooth movement
i move the snake with translate and rotate purely, no force stuff, it's a top down 2d game
when snake "mouth" collider enters the "fruit" trigger collider, fruit gets eaten
snake grows
i remember i (had to) put a rigidbody in the mouth object
had to or it wouldn't trigger iirc
that's so weird to me thogh. not sure if i'm making sense.
i mean, there are no physics anywhere.
why do i have to place a rigidbody in order for the game to detect the "touching" or "overlapping" of two areas (colliders in this case)
hmm. seems i'm probably looking for a "kinematic"-rb-snake and a "static"-rb-fruit
it's probably how unity would want me to do this
yes
however i'm not sure i wanna use MovePosition and MoveRotate.
i don't want forces, i'm specifying how many pixels i want it to move, and i'm controlling velocity by script
oh then that's awesome
so it teleports, but collides along the way lol?
if you're using continuous collision detection, yes
omg i'm going to have to rewrite my whole snake body movement script
it was just a list of transforms.
i guess it's about to get a lot more complicated
collider and otherCollider is SO unintuitive
collider refers to the OTHER
and otherCollider refers to myself?
is it really like that or i'm missing something?
snake script's OnCollisionEnter's collision.collider returns info about the fruit's collider?
and collision.otherCollider returns info about the snake's own collider?
fr
lol something's definitely wrong
.collider is the other collider (the object you collided with)
Then once you get a contact point, there's .thisCollider (yourself) and .otherCollider which is like the Collision's collider property above
but collider and otherCollider are giving me different results, they're behaving invertedly
I'm facing another similiar issue for some reason
hmm i wonder if that might be happening because i'm using transform.translate to move them (and not MovePosition)
Probably
A nullreferenceexception
A collision can have multiple contact points
Ah I was looking at the 3D Collision class, which is different hang on
Yeah seems like otherCollider is yourself, docs are not easy to read on that
the names used are not intuitive
"the incoming collider" - well both colliders are "incoming", it's relative
besides it's inconsistent with how the 3d version works i guess
As for the thisCollider and otherCollider, you need to get a contact point for that using GetContact(), they're not on the Collision2D itself
Great, for 2D they're not named the same as for 3D!
ContactPoint2D's thisCollider is just collider
Why don't you use collision.tag == tagname ?
but is that "collider" really referring to the script object's collider? and not to the collider of the other guy it hit?
Actually, no, it's the collider of the other object
otherCollider is yourself, wtf were they on when they decided on the naming
see what i'm saying
tried to google "unity collider otherCollider inverted" but no luck
i refuse to believe nobody ever saw that
i'll take some time to write something on discussions and see what people say
I'm trying to move my project from editing in windows to linux. I have Unity 2022.2. When I opened the unity editor to the project in ubuntu I got a huge number of errors all saying that GraphicsFormat.R8_UInt (I'm trying to set a RenderTexture.stencilFormat) is unsupported. However when I look online I see this suggested as the most commonly supported format (https://docs.unity3d.com/2022.2/Documentation/ScriptReference/RenderTexture-stencilFormat.html).
How can I figure out what formats I can support / is there anything I can do to make this format supported?
Thanks sorry
i think i've solved the mistery on "collider" and "otherCollider" naming choices
at some point in the past there was no "otherCollider" (it isn't hard to referece one's own collider to get info)
it was just "collider" and refered to the "other guy"
then they implemented "otherCollider" but left "collider" referring to the other guy (and otherCollider to oneself) so people wouldn't need to rewrite code or something
only reasonable explanation
I'm rotating object's localRotation in code. The snippet looks like this.
transform.localRotation = Quaternion.Euler(stopAngleAdd, transform.localRotation.eulerAngles.y, transform.localRotation.eulerAngles.z);
the stopAngleAdd just has the value 8.
When doing this the objects stop either at 8, 0, 0 in rotation (which is what I want)...
Yet other ones stop at 172, 0, 0...
I noticed this is 180 - 8, which is the same value as stopAngleAdd, so I guess I'm missing something with Quaternion.Euler?
the objects could have any degree on the x-axis when the snippet is run, so we never know from what rotation this is done.
Hey, can I reinitialize an array? Will it keep the previous elements if I make it bigger? Or should I just use another array?
If you want to make it bigger, I'd suggest using a List instead.
this way the length is variable.
Hmm let me think maybe I'm going about this wrong to begin with.
EulerAngles are derived from the internal quaternion. Euler angles can represent the same rotation in a number of ways, and you have to account for that
Okay...
"the same rotation in multiple ways" meaning (0, 0, 0) = (360, 0, 0)?
I'm not sure exactly what this entails I think...
More like: 90, 0, 0 might be the same as 0, -90, 90 (please don't test this, it's just an example)
Which is why constructing a rotation from incomplete individual portions of a euler angle that was derived from the internal quaternion is a bad idea
if you're doing this sort of thing it's generally better to keep track of your own individual rotation values and apply them to the transform
instead of reading back from the transform and hoping the representation in eulerAngles is what you expect
Why are EulerAngles used for to begin with? Idk much about it but I'm pretty sure you need only two variables to completely define an angle right?
What do you mean? They are the rotations around X Y and Z
So... in my case it would be a better idea to calculate the rotation needed to end up where I want and apply it?
They are only used for authoring and utility purposes, and in some specialised places like animation
Well you need only 3 variables to define any point in space from what I remember
But distance shouldn't really matter
If you're interested in angles only
You can go (x,y,z) or (r, phi, theta)
I'm not sure what your complete setup looks like, but I recommend keeping track of two floats for your yaw and roll, and use Quaternion.Euler(stopAngleAdd, yaw, rol); instead of grabbing from the transform. But I have no idea if your setup allows for this
That's what Euler Angles are though, X Y Z rotations. Are you asking why we use Quaternions?
It's because they don't suffer from gimbal lock
They also interpolate directly instead of having weird axis problems
ok thanks for the explanantion, I'm going to google those words 😄
Okay, I see. I'm only interested in changing the x-axis's rotation of the object, but I still need to keep track of the other axes to make sure they don't "interfere" with my x-axis-number as it might be interpreted differently if the Z and Y values are strange.
Does that make half-sense the way I wrote it?
I think this makes sense as it goes back to "90, 0, 0 might be the same as 0, -90, 90"-kinda deal. Yes?
Yes, that is likely your issue
Another option is to use a compound transform that only applies a rotation in that one axis so you don't have interference from the other rotations
This sounds great for this specific use case. I googled compound transform and found nothing though. Is it saving a specific vector and using it to apply rotation? How would that look?
Just having another transform under this one
Two transforms in the hierarchy instead of one
ahh I see. That way I'd always know the values of the other ones. Hah, that's an interesting use - never would have thought of that.
I'll try the first method and do the other if I can't figure it out. Thanks a lot :)
is there a simple solution to outlining the voxel that a player is looking at if all the voxels make up a single mesh?
if each voxel was its own mesh then that'd be a lot simpler but they're all a part of one big mesh
i just wanna know if theres a simple way to deal with this or if its gonna be way outside the scope of this project
!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 should clarify: i want to highlight just the face that the player is looking at
why isn't this spawning the grass where i need it to, the grass tile needs to spawn anywhere between the last tile and 3 tiles in front of it https://gdl.space/elubicayet.cs
make a sprite that is just the border highlight you want, raycast from the player to hit the mesh, then use the normal / point of the raycast hit to place the sprite in the right position and with the right rotation
you can get the correct position by rounding then adding an offset, and then just set the forward of the sprite to be the hit.normal
by sprite I just mean something like this
How do I "name" methods like Awake, Start, OnGUI, Update, LateUpdate etc.?
yes, this kind of questions one more time
you cannot name them to other name
i heard that unity engine find these methods through reflection
no, I do not mean it
I mean
What do you mean by this? You name them as documented so Unity calls them
!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 mean, do I call them "Unity's methods" or "Built-in methods" or "MonoBehaviour methods"?
"Source Methods" ?
Unity messages
methods ??
Message functions, whatever you want to call them, include the word message and people will probably know what you mean
For code samples, see the individual MonoBehaviour methods.
I have a score manager script that increases the score based on height difference. It's working as expected, but instead of increasing the score in the Update function, I want to create an event. I know how to create an event, but I need suggestions on how to trigger that event. For example, in a coin-based score system, touching the coin triggers the event and increases the score. I want to implement a similar concept in my game. Any suggestions or examples would be appreciated.
using UnityEngine;
public class ScoreManager : MonoBehaviour
{
#region Variables
[SerializeField] private Transform player;
// Example - If the scoreIncrementHeight is 2, it means that if the player moves up by 2 meters or 2 grid units, their currentScore will increase by 1.
[SerializeField] private float scoreIncrementHeight = 2f;
private float lastRecordedPlayerHeight;
private float currentPlayerHeight;
private int currentScore = 0;
private int highScore;
private const string HIGHSCORE_PLAYER_PREFS_KEY = "high_score";
#endregion
private void Start() {
currentPlayerHeight = lastRecordedPlayerHeight = player.position.y;
highScore = PlayerPrefs.GetInt(HIGHSCORE_PLAYER_PREFS_KEY);
}
private void Update() {
IncreaseScoreLogic();
}
void IncreaseScoreLogic() {
currentPlayerHeight = player.position.y;
float heightDifference = currentPlayerHeight - lastRecordedPlayerHeight;
if (heightDifference >= scoreIncrementHeight) {
lastRecordedPlayerHeight = currentPlayerHeight;
currentScore++;
// High Score
if (currentScore > highScore)
SetNewHighScore();
}
} // IncreaseScoreLogic
void SetNewHighScore() {
highScore = currentScore;
PlayerPrefs.SetInt(HIGHSCORE_PLAYER_PREFS_KEY, highScore);
}
} // Class
```cs
using UnityEngine;
public class CoinCollector : MonoBehaviour
{
public static event Action<int> OnCoinCollected;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
OnCoinCollected?.Invoke(1);
Destroy(gameObject);
}
}
}
// e.g. your ScoreManager class
private int _currentScore;
private void OnEnable() => CoinCollector.OnCoinCollected += CollectCoin; // + on enabke
private void OnDisable() => CoinCollector.OnCoinCollected -= CollectCoin; // - on disable
private void CollectCoin(int value) => _currentScore += value; // do when collecting coin
Thank you for the quick response. What you share is also i found on google but in my game score gets increased based on height difference in that case how to trigger an event
private void Update()
{
currentPlayerHeight = player.position.y;
float heightDifference = currentPlayerHeight - lastRecordedPlayerHeight;
if (heightDifference >= scoreIncrementHeight)
{
// Trigger the event here
}
}
But in this case, using event is no good because what i am doing before is same as this
I don't get it
I don't want to put my increase score logic in Update, that's why I am using event to make my score manager optimize.
Sorry English is not my first language, that's why its hard for me to make a clear point.
my English is poor too, continue, please
yes, I have shown you how to do this without using Update
oh, I see
but I still think you need to trigger it in Update
do you still need to trigger in in OnTriggerEnter?
or just within Update?
unfortunately you have to do it in update to continue check whether the new input data is > than old record
No, in my game score increases based on height difference, I don't have any coin using which I can trigger event inside OnTriggerEnter
ok, so you should do it in Update, LateUpdate, FixedUpdate
Ok got it
there is no other option, as far as I know
So last question, inside which function I should call my increase score logic, which is more optimize
This point is clear now.
I wound call it in Update
what if you have a trigger placed so the bottom is at your previous highest point, then anytime you are within the trigger, send the trigger higher
I also heard inside FixedUpdate only put physics related logic
I guess, yes
now the physics engine have to keep track the one more collider and fire the event if you touch it
Therefore it's the physics engines problem, not mine
U can put other logic inside, but if you're looking at highest point you'll likely want to do that frame by frame (update)
Got it.
you just throw the workload from your logic to physics engine in Fixed update....
So its not a good way to put other than physics related logic in Fixed Update right?
i just reply to the idea of using collider
the problem is wherever you put it you "optimize" it by changing it sampling interval
Got it. But I am little bit confused with Fixed Update function, can I put other logics which are not related to physics inside Fixed Update?
you can
Is this a good way? Everyone does it?
if your logic need to sample in constant time interval then you may want to put it in fixed update
but apart from physics i cant come up with other example
Thank you everyone for your quick responses.
well sometimes u cant really separate out some logic. Like if you need to compare values (the height), check if something happened, then apply some physics function, u cant just take those comparisions and place them in update. Most of what I have in fixed update isnt pure physics functions
but most of it is eventually used for physics
Got it.
hi im trying to make a platform fighter (similar to smash bros) and i was making the knockback functionality.
according to the wiki, this is the knockback formula used in the game. what is this function exactly returning? how can i apply knocback based on whatever this function returns? do i just multiply the value to my velocity? i did try that but it didnt really work. also how can i get the angle for the knockback and stuff too?
can u send the link on this page? it should define what these variables are
i have an understanding of what the variables are
i just dont know what value im getting
like
what im supposed to be doing with it
thats the link
the value returned is just a number, so they likely have an angle they apply this force at
i tried getting an angle but its not working
my idea of the angle wwas
the angle used seems almost arbitrary, it says it depends on the players gravity but thats likely just due to the formula
transform.position of the player getting attacked - whatever the centre of the attack collider is returns the direction
u probably have to make it up per move tbh
and then for angle i saw some thread doing something like this
I assume that wont really work for a lot of interactions, imagine a tall and short character fight. one would only launch the other down towards the floor
the angle?
oh yeah that makes sense
how else can i do this then?
get the angle i mean
like the angle where the player is supposed to be launched towards
and im assuming the returned value of this function is the force that is to be applied
I dont know much of how the game works, I really would just make up an angle depending on the move. At least this way, moves will consistently launch in a certain direction
yes i think so too
but how would the "making up" work
what im tyring to get is
wait let me draw this somewhere
ok this is confusing but the idea is
as in you predetermine some range of angles, this is just like game design, not a coding calculation. The calculation is just going from the left or right vector, to the rotated one
blue is the player getting hit, red is the attacking collider, and green is the direction the player gets thrown toward
the green would be like 45 degrees then, thats really all. You just associate some angle to moves
this seems more like something u need to watch more than me :p
i dont really understand how they get that exact angle
like where they derive it from
some parts of the wiki you linked still leads me to believe these angles are predetermined, but either adjusted or the force is adjusted based on factors
yeah i did watch it but didnt find anything about the angles
why
var folders = AssetDatabase.GetSubFolders("Assets/Silex-Materials_Pack/Textures");
with Debug.Log(folders); returns nothing System.String[]
while trying to print one element of the array returns it ?
can you print the whole array without looping
one part in the wiki states
In Ultimate, moves that launch at angles between 70° and 110° now instead cause characters'....
which further makes me think that the angles are predetermined, but adjusted
you can with string.join, but you should just loop through. Also debug the length to see if its truly nothing
idrk much about it but the general idea i got is that they first derive the angle, and then perform some sakurai angle thing based on that initial angle and the knockback from the attack
yeah i dont either lmao
know what it means
alright ill try taking a look at the wiki again and let you know if i get somewhere
really for your game, just getting something working is better and then try to adjust it
you dont need to make a smash clone. And not many people are gonna notice your angles dont 100% line up to their calculations
Predetermined angle + adjustment due to weight, place hit at, force, and health are perfectly fine
very likely the angles are hard-coded per hit box (exception is the sakurai angle which has some conditions) https://www.ssbwiki.com/Hitbox
A hitbox or collision bubble (sometimes hitbubble) is the main structure for how attacks are executed in most fighting games. Attacks have one or more hitboxes associated with them, and when these hitboxes overlap with a target's damageable area (often called their hurtbox or hurtbubbles), the attack is considered a hit. Hitboxes are invisible a...
i see
that makes sense
Hey, one question, typically in voxel based games, how are voxels selected for example for digging?
It is an isometric game but the camera can rotate
Screen space (2d rect) or world space? A player presses the mouse button and drag it, then drop.
I would say screen space. What do you think?
In 3d model softwares like Maya, it is screen space by default.
Thanks
hi, sorry for asking
did anyone know how to connect an external nfc reader to unity?
hi, is this code correct for a 2D game?
!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.
you’ll want to use a 2d raycast so that it can detect 2d colliders https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
thanks
Hey so i have a little Problem, if i write something with Input.touches it doesnt do it. Anything that has this in it for ex. Debug.log it doesnt do it and i didnt find anything about it
hey, so something really confusing is happening
{
float prevAngle = 0;
for (float i = 360/steps; i <= 360; i=i+360/steps)
{
Vector2 vertex1 = new Vector2(this.radius * Mathf.Sin(prevAngle), this.radius * Mathf.Cos(prevAngle));
}
}```
For some reason, it's not recognizing the multiplication operator within the Vector2 object instantiation.
And so it's throwing an error instead of doing multiplication
Anyone know why this might be the case?
The code for the entire class is this:
{
private Vector2 center;
private float radius;
public Vector2 getCenter() { return center; }
public float getRadius() { return radius; }
public void render(float lineWidth, float steps)
{
float prevAngle = 0;
for (float i = 360/steps; i <= 360; i=i+360/steps)
{
Vector2 vertex1 = new Vector2(this.radius * Mathf.Sin(prevAngle), this.radius * Mathf.Cos(prevAngle));
}
}
public Circle(Vector2 center, float radius)
{
this.radius = radius;
this.center = center;
}
}```
I really don't see a reason that it'd struggle to identify the multiplication operator.
Actually nvm, I just restarted visual studio and it fixed itself. Weird bug with the IDE ig?
how do i decide between a behaviour tree and a state machine? is it simply an issue of complexity? I have a simple AI that at this point will only roam and chase the player upon line of sight.
FSM if you deal primarily with events that happen on state transitions, BT if you are primarily concerned with sequencing a non-trivial action plan over time. Ideally you combine both: FSM handling triggers and implementing state’s internal behavior with shallow BTs.
Error: I keep getting the error parsing infinity while selecting a random string from my json array, It does this at random and I have no idea why. I have a temporary fix at line 49 but it is making the scene restart multiple times and is just not pleasant one bit
Snippet:``` void Start()
{
_openAI = new OpenAIApi(openAIKey);
_client.DefaultRequestHeaders.Add("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{uberDuckKey}:{uberDuckSecret}"))}");
// Pick a random topic
List<string> topics = JsonConvert.DeserializeObject<List<string>>(
File.ReadAllText($"{Application.dataPath}/Scripts/topics.json"));
blacklistPath = $"{Application.dataPath}/Scripts/blacklist.json";
blacklist = JsonConvert.DeserializeObject<List<string>>(File.ReadAllText(blacklistPath));
topics.RemoveAll(t => blacklist.Contains(t));
string topic = topics[_random.Next(0, topics.Count)];
**Full Code:** https://paste.ofcode.org/QYQsqkuvYuU9JgFf8vsGGS
@swift falcon don't cross post.
can i group my events under a dropdown like PlayerInput has its events grouped under the "Events" dropdown?
just for the sake of tidyness?
is it possible to detect a specific collider from a gameobject by the material name with collider.sharedMaterial.name, or should i be using something else to detect that specific collider? As there is a main collider for collisions and a collider that should only work to be detected by other specifical collider.
How do i get a string[] of all textures given the folder path
you mean string[] ?
string[] textureFiles = Directory.GetFiles(folderPath, "*.png", SearchOption.AllDirectories);
.png probably
using System.IO;
it should be shown when you press Alt + Enter
is it local path or absolute path
C:\ ...
I guess both should work though
NullReferenceException: Object reference not set to an instance of an object
is your path correct?
I guess no.
yes
@vernal plank try this one
i dont have windows i can get the path from terminal thanks 😄
we are not mind readers. in the future show the complete error message and the line of code it points to
okay lol its not giveing me any line number i guess
this is the only line that giveing a problem
it will be
it gives when you click on error
here
yes, check your path
make sure it exists
the only way that line gives a null ref if is folderPath is null
Thanks the path was missing / at the end
were you rewriting it or what? 
if you had copied the pass, it won't be missing anything
i was literally listening
the path it self from an array of paths lol
make sure to write it with @
filePath = @"blabla";
you can avoid double "//" when using "@"
/home/larsitsmeash/Ash-lib/
I have a ScriptableObject that contains some properties that are used in game. When I change the values in the inspector, it seems all fine. When I deselect and select it again, all values are back to what they were before I changed anything. And they are not reset to their default values, just some values I used a while ago. Currently it's impossible to change the property values now. It just always resets back. Any idea what could cause this?
I dunno actually
Yeah it's a C# feature called verbatim string, that ignores escape sequences like \n or \\ so paths are easier to make
and yes, I meant \
thats windows not linux
macOS too?
linux is much smoother
windows uses backslash which is treated as a special character, linux uses forward slash which is not
when it comes to paths and directories
@"a\b\c"
// same as
"a\\b\\c"
macOs is linux
that's what I was talking about
what?
what did you think it was based on?
yeah and it doesn't have c: too
MacOs is linux with a custom GUI
even tho mac is not linux both they are unix based
so they are pretty much have the same terminal and same structure but macOS is locked
it's not so
or in a better world mac is more restrictive
restrictive?
is it comfortable to use linux?
once you get used to it yeah
when you starting out its pure pain
once you get used to it you would never go back to windows
unity seems fine on linux
never had an issue
i also use unreal godot
zbrush
substance designer
Scratch too?
what ?
sounds like you should consider using something one
Scratch is also GameEngine
ill look it out
btw you can try linux on a live USB env
the hardest one
https://scratch.mit.edu/projects/editor/?tutorial=getStarted
before you even install it
that's something I won't probably understand 🫠
you dont have to install it as your daily driver to try it you can get a USB stick and boot your system from it
oh, I see
I am ok with windows 😁 thanks though
Hello everyone !
I am trying to code a script that would put a UI element A at the same position and size as another element B which is elsewhere in the hierarchy.
I tried changing the transform.position, including before/after changing parents, but I can not manage to get a good result.
Anybody knows how to handle that ?
Each time I deselect my ScriptableObject asset it reverts all changes to properties back to what they were before. I never had this issue before, what could it be?
In fact I can only change the values by editing the .asset file in a separate texteditor now...
Show the code for it
And explain which things you are trying to change
i have a question in unity's editor.
say i have abstractclass base, and said class have 3 classes that implement it: class1, class2, class3.
i have another script which has public base variable
is it possible in the editor to assign class to variable
Short version of it (it has quite a lot of properties):
[CreateAssetMenu(fileName = "settings", menuName = "Settings")]
public class Settings : ScriptableObject
{
[Tooltip("What temperature will be tundra.")]
[Range(0f, 1f)]public float TundraThreshold = 0.3f;
}
If I change this value in the inspector, for example to 0.2, when I deselect the asset, it will just revert it back to what it was before, no matter what.
I must say I'm pleased I can at least change it by just editing the asset in a txt editor, I was going nuts before I realized that simple solution
more in depth:
public class DataClasses
{
public abstract class Base {}
public class FirstClass : Base {}
public class SecondClass : Base {}
}
and in another script:
public class Whatever: MonoBehaviour
{
public DataClasses.Base variable;
}
i want in the editor to choose if variable is FirstClass or SecondClass
Without making a custom inspector for your Whatever class, you can't. Unity doesn't support polymorphic serialization
you can use SerializeReference for this
another option is to make your base class a ScriptableObject, and all your subclasses will have to be assets
can you give an example on how i can do this?
pls don't 🥹
Why not? It's data, and he won't have to create an inspector or do anything hacky to choose his variable
i can't seem to get this to work in the editor at least, as i understood it, it just helps unity serialize objects correctly instead of just saving base
SerializeReference has never worked well for me, if it's simple you can use my suggestion, otherwise you might as well use something like odin
read the docs very carefully, see the Dos and Donts.. and the docs is very throughly explaining on how to use it
it's one of the most beautiful thing ever happened to Unity 🥹 ... and for once the docs is very good at explaining how to use it properly
I strongly suggest you try and use it first. Their example is janky for a reason
That's what i did:
public class DataClasses
{
[Serializable]
public abstract class Base {}
[Serializable]
public class FirstClass : Base {}
[Serializable]
public class SecondClass : Base {}
}
public class Whatever: MonoBehaviour
{
[SerializeReference]
public DataClasses.Base variable;
}
bruh
?
are you sure you read the docs properly?
[serialiazereference] Base baseClass = new FirstClass()
Hi, I'm currently watching a video to implement the A* algorithm in unity, my game is a top-down 2d map (like enter the gungeon) but his game is a top-down 3d map . he Wrote a code to adjust the weight of each grid(like, in snow you are much slower than flat surface) which doesn't work for me because I can't do the same in 2D. Any idea how to do the same in 2d? his code:
i use physics2d.overlapcircle
Are you using an actual Grid component?
If so, you can convert a world-space position to a grid-space position.
(and then find the tile for that grid-space position, if one exists)
or is this not tilemap-based?
for grid, i built a grid class myself. and yes tile map based
can you take a world-space position and turn it into a grid-space position?
i have a method for this
then you just need to figure out which grid space you're on and then get the tile at that space
no need for physics at all
how can i do this without physics?
by doing this.
your question is "how do I find the tile at a certain position?"
you don't need to do any raycasting for this. you already have a regular grid of tiles.
Oh sorry I misunderstood, I can't do that.
Then I'd suggest implementing that.
It's very important to be able to convert back-and-forth between world and grid space.
I have two separate grids, one for a* and one for painting. I need to create a method to check my drawing grid at a* grid position, right?
Right.
You want to know what kind of tile is present at that spot
so you might need to go A* grid -> world space -> drawing grid
I didn't even know I could interact with my drawing grid.
lol
thanks
i mean, it's your grid :p
Is it possible to make myProperty.Length return whatever I want ?
myProperty is obviously a string property
.Length will be a property from the string
maybe you can derive from the string class and override the .Length property? sounds weird
it's impossible to change
you'd have to return your own modified string type
for example
private string foo
{
get => bar;
set => foo = value;
}
// foo = "fdsfsdfsdfsdfs"
// foo.Length; // returns e.g. 0
is it possible?
of course, overide the Length variable
I need it to return 0, when it is "\u200B"
the non-printing space character?
yes, zero-width space
when the string is nothing but a zero-width space?
yes
are you trying to count visible characters here?
my string is either something or "\u200B"
I need it to return 0 when it's "\u200B", otherwise just normal Length
...
if (value.Length == 0)
value = "\u200B";
_textComponent.text = value;
...
perhaps you can just keep value as an empty string
and then set the text component to contain a zero-width space anyway
no.
I access _textComponent through text
private string text
{
get => _textComponent.text;
set
{
if (value == null)
value = string.Empty;
value = value.Replace("\0", string.Empty).Replace("\u200B", string.Empty);
_caretPosition = value.Length;
if (value.Length == 0)
value = "\u200B";
_textComponent.text = value;
AlignCaret();
}
}
anyway, how do I override Length, as you have mentioned earlier?
You can't, you're better off using an extension method (cannot make extension properties in C#) that returns your desired length, and call that one instead
oh, true, extension methods would help here
you just couldn't clobber the original property (even if you had extension properties)
ok, I simply check text now then
_caretPosition = (text == "\u200B") ? 0 : text.Length;
I haven't thought of it first
they cannot
zero width space does not exist on keyboard
well, sure, but neither do emojis
and user cannot copypaste in my input field
so you say there is u200B in emojis ?
ah yeah, if you can't even copy paste, then i guess it's not relevant
I just think it's good to not have any "special" strings
it'd be nicer to have a flag that tells you if the field is empty
I need /u200B, because it's the only normal way to access TMP_CharacterInfo
ah, so you need to have something in there
yes, I do
i mean you would still have a zero-width space in there; the "text" property would just be an empty string
well, text returns _textComponent.text
I don't think I should seperate them somehow
and that's exactly what TMP_InputField uses
I have been investigating their code
m_TextComponent.text = processed + "\u200B"; // Extra space is added for Caret tracking.
!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.
why does Vector2.up, in the context of transform.translate gives me a "local" up (that points to the forward direction my transform is facing), but in the context of rigidbody.MovePosition gives me a "global" up (that points always "up" regardless of my transform's rotation)?
Doesn't matter where you use it
Vector3.up will always give you the global Up (Positive Y axis)
I think you are using local while using translate
It's transform.up that will give you the local y axis of the object
Because that's how translate works. It interprets the vector as a local vector
Hey guys, I have a script in my game called rhythm cube. I have a list of references to the copies of the script on my objects in the scene. I use this code: foreach (RhythmCube cube in rhythmCubes)
cube.StopAllCoroutines(); To try and stop all the coroutines the scripts are running, and it doesn't work. Any ideas?
If you look at the docs there's actually a second parameter where you can specify Space.World or Space.Local
It's simply just because that's how they wrote Translate
Define "doesn't work"
It doesnt stop the coroutines. I can see that they are still running after this code has been triggered
there's a MovePosition overload that allows me to tell it Vector2.up is local?
YOu'd have to show the code, clearly you've messed something up along the way
no
there's a Translate overload that allows you to tell it whether it's local or world space
read the docs
MovePosition is always in world space
Just use transform.up
When you want to move it locally
yeah i just did.
i was wondering if there's a classier way of achieving the same result but with MovePosition (to still process the physics stuff etc)
What uv said
Here is my code https://paste.ofcode.org/RCwxjUPcdUyaxdAA8C99bD
but if i use transform.up won't it not do physics stuff (collider/rigidbody)?
i was told to use MovePosition instead of transform.Translate exactly for that reason
As per line 49 - all of your coroutines are running on THIS object, not the cubes themselves
unless there's some other coroutine involved
Oh, that makes sense
I guess the coroutine doesn't have to only run on the script its code is from
In other words - replace:
foreach (RhythmCube cube in rhythmCubes)
cube.StopAllCoroutines();```
with:
```cs
StopAllCoroutines();```
thanks
it runs wherever you called StartCoroutine from
transform.up not Vector2.up if you want local
transform.up is just a vector
it's just data
it doesn't do anything
you were told to use MovePosition instead of Translate
and that's still true
note that you can and probably should replace this code with:
rigidbody.velocity = transform.up * moveSpeed;```
MovePosition doesn't actually respect collisions properly
especially if this object is dynamic
no need for the deltatime stuff in this case?
Should I use a CharacterController or RigidBody for an FPS game with vaulting, jumping, etc. Or is this simply a matter of personal preference?
But doesn't setting velocity mean it will override the physics calculations unity does?
Correct me if I am wrong
deltaTime will break it.
velocity already is a per-second quantity
which physics calculations in particular
MovePosition is much more disruptive to physics calculations than setting velocity
it' kinetic btw. all manual move
Yes should always be using AddForce for non kinematic bodies
then either will work about the same
wow it worked flawlessly
You know that the result of AddForce is just to modify the velocity?
Well the velocity calculations for that frame?
Yes but it does consider the mass?
and it does make MUCH more sense that "setting velocity" is way better than just "teleporting" to maintain physics alright
sure but that's just a matter of math
deciding which velocity to set to
which you can do yourself too

and solved my second problem which was this ugly conversion of "transform.up" into "new Vector2(transform.up.x, transform.up.y)" to correct some "amibuity" error VS popped up in some Vector2 vs Vector3 stuff
seems velocity will accept both?
this is because you had math involving a Vector2 added or subtracted from a Vector3
both V2 + V2 and V3 + V3 are valid
and it doesn't know if you want to convert the V2 to a V3 or vice versa
since both are valid
ultimately it doesn't matter but the compiler needs to just be told which
so it's an "error" i could've just ignored?
e.g.
rb.MovePosition(rb.position + (Vector2)transform.up);
rb.MovePosition((Vector3)rb.position + transform.up);``` would both work
AHH i spent like 30 minutes trying <>, (), [], "as" lmao
didn't realize it goes before the variable
as would work too but is kinda sketchy here lol
rb.MovePosition(rb.position + (transform.up as Vector2));
although idk if that would get angry about nullables or something here
https://hatebin.com/oigdrmybhr | https://hatebin.com/igfkydeuet i made these two scripts with help from youtube (thats why i want to make a drawer but its with the "doorOpen" or "doorClose" name) to make a drawer that open and closes i dooed the animations of it opening and closing and i maded this 2 scripts but its now working when i aim in the drawer my crosshair dont turn red and i cant press mouse0 to open it, pls help
don't crosspost.
now i wonder if there's some rigidbody.rotationVelocity i'm not aware of lol
yes it's called... that^
loooking at docs == big brain
A new fantastic point of view
well, it's different from velocity...
it's a good trick
(or not spin, you know, depending)

oh yeah i just want to replace my rigidbody.rotation with this new guy
good idea
dude i already feel like a pro coder
position : velocity :: rotation : angularVelocity
scale : ?
actually, that's a good indication that scale is "weird" compared to the other two fundamental properties
i'm even using overloads to avoid having to come up with weird names that would probably confuse me
Turn(CallBack context) subscribes to an input event and calls a local Turn(no arg) to make stuff happen
i just read values directly from actions if I need them every frame
InputActionReference is lovely
i explained that wrong though
i have a Turn(context) which just assigns values to a local var (just so i don't need to do that every single fixedupdate)
and another Turn (that is necessarily executed every fixedupdate) that grabs value from the local var
i guess all i did was take a check out of fixedupdate and have it happen only when value changes (inputaction event)
not a big deal i guess but personal progress
is it OK to link chatGPT "conversations" (the new feature they put out)?
in the subject of unity coding obvisouly
It's irrelevant here, especially in this channel.
i would rather not be exposed to the spam machine
it does get things wrong though lol
for example it also thinks (probably because of the variable names) that "collider" refers to ourselves and "otherCollider" to the 'other guy', however it's the other way around
yes, because it's a large language model
it produces text that is likely to follow the prompt
ask it how to set the static friction of a 2D physics material
it will probably explain how to do that, even though 2D physics materials do not have static friction
(i would be impressed if it actually correctly responded that there is only friction)
it is, and it probably uses its training with the unity docs to answer that kind of stuff
and from reading unity docs you really think "otherCollider" is the other guy.
only through you experience you learn it's the other way around
well, no, you read the docs and they say what the variables mean
what do you mean?
you read the documentation. it tells you the answer.
collider:
The incoming Collider2D involved in the collision with the otherCollider.
otherCollider:
The other Collider2D involved in the collision with the collider.
all the docs say to differentiate between them (besides referring to one as "collider" and the other as "other collider" is to say "collider" is the incoming one)
isn't incoming the guy which is moving?
it's the one that is coming in and hitting us
i agree that otherCollider should have been named ownCollider or something
exactly
to name something "otherCollider" while it's giving information about "myself" (the script's object) is like making an effort for people to confuse it
the other problem with the word "incoming" is
if A (script) is moving and hits B
B is the "incoming" guy (despite it being a static object)
is it the same with Collider (3D)?
at least it's described much more directly (and unambiguously)
Oh hey, still on this? Yeah 3D is much more explicit on this even for contact points, thisCollider, otherCollider
private Vector2 CreateRandomDestination()
{
Vector2 currentPosition = transform.position;
float newX = Random.Range(-maxDistance, maxDistance);
float newY = Random.Range(-maxDistance, maxDistance);
Vector2 destination = new Vector2(newX, newY) + currentPosition;
while (DestinationBlocked(currentPosition, destination))
{
newX = Random.Range(-maxDistance, maxDistance);
newY = Random.Range(-maxDistance, maxDistance);
destination = new Vector2(newX, newY) + currentPosition;
}
return destination;
private Vector2 CreateRandomDestination()
{
Vector2 currentPosition = transform.position;
float newX = Random.Range(-maxDistance, maxDistance);
float newY = Random.Range(-maxDistance, maxDistance);
Vector2 destination = new Vector2(newX, newY) + currentPosition;
if (DestinationBlocked(currentPosition, destination))
{
return new CreateRandomDestination();
}
return destination;
is one of these solutions preferred over the other?
i guess the recursion is doing the same thing
recursion could eventually cause a stack overflow if it goes on for a long time
one is a potential infinite loop, the other is a potential stack overflow, neither of which are desired outcomes
yes, also set a bool to know that it has 'timed out'
does anyone know how words in TMP_Text are transferred to a new line?
perhaps "where?"
or in TextMeshProUGUI..
I guess in GenerateTextMesh()
so when making a list of gameobjects that compose the player (snake segments in my case)
i see people using a list of "Transforms"
why not "GameObjects" or even "Rigidbodies" instead?
because they change Transform's values
It goes down to what is accessed a lot when using a list item. If you store GameObject but access their position, you'll have to do .transform.position every time
and it sounds more logical to use Transform, not GameObect or Rigidbody
so if i'm going to mess with velocity and angularVelocity instead of positions and rotations directly, i should probably reference a list of Rigidbodys right?
ah cool! this sounds a lot easier than the shader solution i was thinking of
yes
unless you don't need its Transform
Is it possible to make a scene reload if a certain error pops up in the console? Let me know.
Texture propte = material.GetTexture("_MainTex"); this is doing what expected
material.SetTexture("_MainTex", extexture); this is not assighing the texture
w h y
Material material = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
do i need render component
Am trying to change material texture with editor script
the material has a graph shader
but i dont wanna change the graph shader
i wanna change the material instance (its a normal mat)
bascilly the second one is retuning no error i wonder if i can debug it somehow and see what its doing
is a static class adequate for implementation of a game manager (unique) class?
public class AssetDatabaseExamplesTest : MonoBehaviour
{
[MenuItem("AssetDatabase/printmat")]
static void SubFolderExample()
{
var folders = AssetDatabase.GetSubFolders("Assets/Silex-Materials_Pack/Textures");
string foldvar = folders[3];
string[] files = Directory.GetFiles(foldvar+"/", "*.png", SearchOption.TopDirectoryOnly);
string wellyay = files[0];
string materialPath = "Assets/Silex-Materials_Pack/Materials/test/Mat_test.mat";
Texture extexture = (Texture)AssetDatabase.LoadAssetAtPath(wellyay, typeof(Texture));
// Texture2D extexture = (Texture2D)AssetDatabase.LoadAssetAtPath(wellyay, typeof(Texture2D));
Material material = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
// Debug.Log(material);
material.SetTexture("_MainTex", extexture);
Debug.Log("well",extexture);
its editor script
its public class i guess
am trying to change the texture of a material
without effecting its shader
make the instance of the clas static
how do i fix this? Bonzi is going forward, like he should, but Peedy seems to sink. They both use the same AI wander script.
The green one has its forward axis pointing down, probably.
But also don't post your question in multiple channels, and especially don't repost your question every minute as soon as it gets buried by other conversations.
Read #854851968446365696 for instructions on how to ask a good question, your code, the debugging steps you took are missing here
I'm running into this really weird issue all of a sudden where Unity keeps tagging some of its own built-in components as not recognizable as monobehaviours
so prefabs lose their links to these scripts
It was happening to NetworkTransport before, and now it's happening to NetworkObjects
If I go into the prefab and reassign the script it "works" but as soon as I exit the prefab and it saves it, it loses the link on the prefab again and shows up as a missing script
does this mean the forward axis is down?
The blue arrow (you're in rotation mode, switch back to move mode) points down
Probably
Well use your eyes, definitely not
It points backwards though, but it might be a setup issue
The blue vector is the Z forward vector and should be pointing forwards, not back
anyone?
Make sure your Move tool is in Pivot Local mode first. These are two buttons above the scene view
yoho friendly ppl
void OnTriggerEnter2D(Collider2D col)
{
if(col.CompareTag("Player"))
{
maxHP--;
ShowFloatingText();
if(maxHP == 0)
{
gameObject.SetActive(false);
}
}
}
void ShowFloatingText()
{
Instantiate(popUp, transform.position, Quaternion.identity, transform);
Debug.Log(maxHP);
}
the pop up text isnt showing for some reason. When i debug, then the hp is properly reduced with each hit, but only after it reached 0, does the pop up GO get instatiated, according to the hierarchy
It'll look like this
still sinks.
Never seen that happen, do you have editor scripts running anywhere? It might be just Unity freaking out once again!
Post a screenshot with the arrows set up to Pivot / Local mode: #archived-code-general message
Have you set up your pivot and coordinate mode yet?
do i necessarily have to attach my "GameManager" script to a GameObject in order for it to execute its awake, start, update etc functions?
yeah it's oddly specific
this is pivot local
Well the blue axis is up now
please review my screenshot regarding pivot and coordinate system for the correct settings #archived-code-general message
make the settings match with what I posted there
Meaning your AI wandering system actually pushes objects along the backward direction
how do i change it
These were probably exported from Blender, but as Blender is Z-up, it's broken
You'll have to export again, with the correct axis settings
What Unity version are you on? Might want to backup then upgrade / downgrade to see if that solves it
I tried punching in "No monobehaviour scripts in the file" in a search and.... Apparently this is a thing! Well, I might be able to solve it with a Reimport All... Fingers crossed.
I'm gonna try this before doing the downgrade since it's a lower hanging fruit
in blender, what next
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
Ask there
Okay... Well, let's look at the axes in Blender
blender uses a Z up
Unity uses a Y up
I think you can fix the problem with your export settings
Yeah I remember seeing that, eh just try random combinations until it works
There's a 1/27 chance of getting it right the first time, good luck!
also this channel is for CODE related issues
this isn't one
if variables are private by default then whats the purpose of using the private keyword
Being explicit about it
yeah, he didn't know that going into this... we diagnosed it down to a modelling issue just now, maybe cut him a teeny bit of slack?
but here's something for @rocky laurel before you go to the modelling help department. This is in the export options. Muck with those.
Did you know that classes and other types that are not marked with an access modifier such as private, are internal by default? So it's not always private, better be explicit about it!
all working. thanks so much for your help!
Thanks for the info
Oh that's actually simpler now, before you had X / Y / Z and individual configurations for each. Way more readable now in that version
plus, by not making something public (and choosing something like private) it limits the scope of what OTHER objects can see that variable (and it can clean up your intellisense suggestions)
but, by default, public variables are SERIALIZED (meaning they show up in the inspector and these values are STORED in scene data or asset data
can i actually get help
But you can add [SerializeField] to force this same behaviour upon any non-public members
and it will only work upon serializable data types
cuz im following the tutorial step by step and this one part isn't working
ask your question, don't ask to ask!
it's faster that way
don't ask if it's okay if you can ask a question
just ask your question
state the problem, let's see how your tutorial is breaking
we'll git er dun
It eliminates the "can I ask you guys something" preliminary question that just wasting some time
It optimizes the time and space here, and as programmers oh boy do we like optimization
so basically it says to add a gird layout group to my toolbar ui image, i can add it, but when i duplicate my inventory slot (like the tutorial says) i doesnt do anything, when it should be spreading them out
oh so basically saying, can i get help, instead you state your problem
okay, we need a screenshot of the UI (that is broken) plus a shot of your hierarchy, plus a shot of your inspector
we'll move from there
can i just send one full screenshot?
go for it
nono that's fine
when i duplicate the inventoy slot it should be looking something like this
but when i do duplicate it it does nowthing
nothing8
nothing***
so they all get centered?