#💻┃code-beginner
1 messages · Page 767 of 1
yes I understand
and etc
I'm just letting you know if you notice most fpv games animate whatever you're holding / arms
wdym?
which part you're confused on?
this
a lot of fpv sell the effect with animating the meshes instead of cam
depending on game, but so usually it doesn't mess with your aiming
weapon moves but camera is static
oh
mines not a shooter
I have extra stuff for the head bobbing
the games going to have sanity and the higher sanity you have the harder you will bob and what not
either way, i've given you already these two options
sin/cos or like use the built in noise from cinemachine
yeah, I just dunno how to use them
do you know how to explain it?
and make it repeat?
I think I understand a way for it to repeat
actually
I can use a while statement correct?
no need
just like use sin with Time.time for example that should give you a simple up and down then multiply it by some val
Time.time?
wait
your telling me
theres a better way. To do
timers?
wth man
See the updated version here: https://www.youtube.com/watch?v=7JcmpBUx4ag
❤️ Become a Tarobro on Patreon: https://www.patreon.com/tarodev
=========
🔔 SUBSCRIBE: https://bit.ly/3eqG1Z6
🗨️ DISCORD: https://discord.gg/tarodev
✅ MORE TUTORIALS: https://www.youtube.com/tarodev
I'm sure if you lookup any these headbob things they have sin somewhere
I wanna make it myself
though I personally prefer cinemachine as it gives more randomized noise added on
instead of copying
alright
I'll just go with Sine
for now
wait its unlisted?
where'd you get this
I had it in my YT playlist for unity since a couple years
alright
Hi
How can disable the gameobject Parent since all the gameobjects childs are disable
what child have to do with parent? just reference the parent and disable it
transform.parent.gameObject.SetActive(false) but its kinda dirty to do..
should I use euler angles or transform.rotation of the camera
Ok
But when all the gameobjects are disable
Example
uh if you want it to go up and down it should probably be position not rotation
The gameobject parent have 3 gameobjects childs
When the 3 gameobject childs are disable, the gameobject parent is will disable
alright
so in the object that keeps count of disabled child have reference to the parent
what are you even showing me here?
so is working ?
More and less
Script to active the gameobject parent
So, this active the gameobject parent but, not their gameobjects childs
well yeah each gameobject has their own active states
So, I create this script
Not entirely sure on how to do it ngl
But I still not working
read whats in the link and you'll understand what the error is telling you
Its fixed but it still doesnt move at all
you never assign cameraPosition back.
value types only copies the values, messing with a copy wont do much if you dont assign it back to something
try it but you would also need to return to "normal" if not moving
doesnt work
https://youtu.be/5MbR2qJK8Tc
maybe this will steer you a bit to something workable
Game devs HATE him, learn this one clever trick to figure out FPS head bob movement forever
Still not working
whats not working? & what are you trying to achieve exactly? this seems overdone where there could be a simpler solution
Anyone understand how to make a camera lag behind whilst rotating it?
i think thats an option in the camera settings
obligatory: use cinemachine
how
my speed variable doesnt work.
using UnityEngine;
using UnityEngine.InputSystem;
public class asd : MonoBehaviour
{
public float speed = 500f;
private float movX;
private float movY;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void OnMove(InputValue movementValue)
{
Vector2 movementVector = movementValue.Get<Vector2>();
movX = movementVector.x;
movY = movementVector.y;
}
void FixedUpdate()
{
if (Camera.main == null) return;
Vector3 camForward = Camera.main.transform.forward;
Vector3 camRight = Camera.main.transform.right;
camForward.y = 0f;
camRight.y = 0f;
camForward.Normalize();
camRight.Normalize();
Vector3 movement = camForward * movY + camRight * movX;
rb.AddForce(movement * speed);
}
}
!code 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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 mb im new
what's speed set to in the inspector?
its set to move a sphere on this absalutly wonderful plane
it moves, it just doesnt scale
@naive pawn
What's the speed set to in the inspector
it was set to 0. i fixed it and set it to 20, thanks for pointing that out
now how would i double the gravity of the ball
set the gravity scale to 2
[Error :Il2CppInterop] During invoking native->managed trampoline
Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at (il2cpp -> managed) Tick(IntPtr , Single& , Il2CppMethodInfo* )
Anyone able to help with this? 
I have a BepinEx plugin working for preventing loss of Hunger, Thirst and Temperature for the player, and I have the objects (clone)'s for NPC villagers but when I try to apply the code to both somewhere along the line it's resulting in this being spammed in the console before I've even loaded into my save
I've tried using ChatGPT to try to troubleshoot this but it seems unable to 
BepinEx is a modding tool, yes? This server doesn't allow modding discussion, best to find somewhere else to ask
Developers for ASKA literally allow mods
unfortunately it's still not allowed here, iirc because it breaks terms of service
But whatever, be facist, I'll just let people know
why are you being weird about it homie
#📖┃code-of-conduct, it's in the box at the top
What a weird childish response lol
i have a question related to architecture...currently, i have a script which spawns units manually(i press certain keys to spawn them), and i wanna automate it in the future. I have another script which controls when the unit gets destroyed(when it goes outside the map). I wanna be able to animate the units in a certain way based on which direction it's currently moving in. for that, i am currently calculating the t ratio inside the script which controls when it gets destroyed. should i make another seperate script for its animation and attach it or just build it inside the destruction script that's already present
I think it might be easier to make a separate script for the animation, and either use the t value of the first script or recalculate it, but that's just based on ease of readability and not on any kind of performance estimations
aight, then i might as well reference it. i guess i need to make a method to return the t ratio in the destruction script for the animation script to use...
Hey guys, I have a very beginner question
I want to enable all children of a gameobject, that have a mesh filter, I thought I did it right, but apparently not
if you've got a public variable storing the t value in the first script, you can access it directly via a reference to the script
like:
TestScript has
public int my_int = 28
Then
SecondScript has
public TestScript otherScript
Debug.Log(otherScript.my_int) //will output 28
will i ever require the t ratio in any other circumstance?
prolly not...
You're only setting meshFilter to be active, and not instances, I'm not 100% sure but I'd guess that's the issue
Are you not planning to use the t ratio to get the direction the object is moving using EvaluateTangent?
Or is that no longer necessary
Aaaah, so, how do I get the gameobject from the list of Gameobjects with mesh filters and enable that?
Do you know?
i can just evaluate tangent in the destruction script
@tired python personally from reading your stuff i would do something like this
I don't know exactly, but what it looks like you're doing is, creating an array of mesh filters that contains the children of your gameobject, combining them all into one mesh called instances, then activating the parent. I'd assume you'd just refer to the gameobject of instances.
actually i'd go one step further and say instead of the unit killing itself, the unit asks the manager to kill it
so, if i get this right, the Unit has a script init which is responsible for both?
keep in mind: Only active child GameObjects are included in the search, unless you call the method with the includeInactive parameter set to true, in which case inactive child GameObjects are also included. The GameObject on which the method is called is always searched regardless of this parameter.
yeah each hard-edge box would be a monobehaviour or some script in general
Ooooooh THAT must be it, because I wanna search through deactivated gameobjects and enable them if they have a meshfilter
i know, you said "enable" them
You may want to split unit stuff into seperate components later down the line if certain units have notably differing behaviour but if your early on i'd just say 1 script per responsible "party" if you feel me
Anyone know how to use direct raycast?
the enemies more or less are gonna have the same type of script running...so pretty sure they ain't gonna have very different scripts
having UnitManager be in charge of middle-manning every job of "managing" the units allows the units, your input manager and whatever automation you want to touch the same system in the same way
Since they're both going to be in one script under this setup, you don't have to worry about sending the t value back and forth anymore
what is that
What do you mean by "direct"?
ya...that was one of the options
I know how to do that using visual scripts, but not code
well. just 3d raycast then
ty
one more thing that's not explicitly covered by the docs (but is visible in the first example script) is, if you want to get a reference to the thing the raycast hit, you can add out hit to the parameters when you call it. Then when you write hit afterwards in your code it will refer to the object hit.
I think I know what I'm doing wrong ngl
Yeah, I just realised as you sent that you need to define RaycastHit hit; beforehand
It was my mistake in the way I described it
So like this
I'm trying to make sure the door checks if the player is close enough
(you also don't have to call it hit lol)
and if it is we can open it
I think I'm doing it wrong ngl
and I might have just figured it out
{
float tratio = aniSpline.ElapsedTime / aniSpline.Duration;
float3 tangentVector = spline.EvaluateTangent(spline, tratio);
Debug.Log($"Ratio t is: {aniSpline.ElapsedTime / aniSpline.Duration}");
Debug.Log($"The tangent is: {tangentVector[0]}, {tangentVector[1]}, {tangentVector[2]}");
}```
``No overload for method 'EvaluateTangent' takes 2 arguments`` is the error that's popping up...
For the direction field, you'll probably want transform.position - player.position
Are you using SplineUtility?
out can't go on its own
oh...gotcha
I cant do hit as well
did you define hit beforehand like I said here? @meager siren
oh thats what you mean
my fault
this is an example of how it might look from the docs
could also declare it inline
with out RaycastHit hit in the raycast?
out RaycastHit hit or out var hit for example, in the argument position
Yeah
Either method works the same, unless there's a reason to use one over the other that I'm missing
Its not working
it makes it clearer what initializes it and what scope it belongs to imo, but it's mostly a preference thing
What should it be doing? Currently there's an if statement with no body
you basically have nested ifs here
its meant to be like this
Im guessing I shouldnt do that?
matter of a fact
I dont even know what nested means anymore
dont even think I ever knew
If you leave out the brackets does it just act as though there's a { directly after the if and a } at the very end of that nesting level (don't know the right word)? I've not done it before
It means an if within an if, or any kind of control statements inside other control statements
What you've got there is nested ifs
Ah, so I did know that. :p I forget things a lot.
Imma be honest he just confused me
I have prior coding experience to C#
Ive done python before. My teacher taught me nested if statements
and I forgot
but thanks for reminding me
There's nothing wrong with the concept of nesting, but currently it might be hard to tell where the problem is, seeing as two conditions have to be fulfilled for the innermost line of code to be executed
yeah
If it's not working the best way to debug it is to put a Debug.Log in each level of the nested if's, with different messages, to see exactly where the code gets to
yeah
And then you'll know which condition fails
When the player changes to a new gun, the gun is instantiated for the player to use. I'm trying to set the "WeaponAnim" value on the player, to the Animator that is stored on the Weapon and the Weapon ScriptableObject. It is being assigned, but my animator is not playing and I'm not sure why.
I have a trigger called "ShotFire" which is being called whenever the player mouse clicks, and I've used Debug.Log to ensure it should be being called. But my animator never starts and I'm not sure why. Can anyone help please?
not quite
you know single-line if statements?
this is basically that
@placid jewel
using UnityEditor.ShaderGraph.Internal;
using UnityEditorInternal.VersionControl;
using UnityEngine;
using UnityEngine.Splines;
public class DamnDeseDucks : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
[SerializeField] private SplineAnimate aniSpline;
[SerializeField] private Spline spline;
void Start()
{
aniSpline.Completed += onComplete;
}
// Update is called once per frame
void Update()
{
CalculateTangent();
}
void onComplete()
{
Debug.Log("Duck will be destroyed.");
Destroy(gameObject);
Debug.Log("Duck was destroyed.");
}
void CalculateTangent()
{
float tratio = aniSpline.ElapsedTime / aniSpline.Duration;
float3 tangentVector = SplineUtility.EvaluateTangent(spline, tratio);
Debug.Log($"Ratio t is: {aniSpline.ElapsedTime / aniSpline.Duration}");
Debug.Log($"The tangent is: {tangentVector.x}, {tangentVector.y}, {tangentVector.z}");
}
}
somehow, the Debug.Log($"The tangent is: {tangentVector.x}, {tangentVector.y}, {tangentVector.z}"); is printing (inf, inf, inf)
window->panels->console
In your t value Debug.Log, can you change the value from aniSpline.ElapsedTime / aniSpline.Duration to directly debug tratio?
you can bring it back right?
Just in case it's somehow not working
right?
check the general tab
tysm
Yeah it's just not hitting overall
heres the funny code
I think I might have given you the wrong vector direction to use
oh vector direction
Vector from points A to B is b-a
So player.position - transform.position
@placid jewel the format of ifs (and control statements in general) basically goes like if ( condition ) statement
that statement could be anything, including another control flow statement, the empty statement ;, or a block statement { ...statements }
to my knowledge, all c-syntax languages obey this
they're both just math, they don't care about each other
if you use them correctly you can use them together fine
So
if (condition) block of code that was meant to be outside the if
is the same as
if (condition) { block of code that was meant to be outside the if }
right?
debug the name of the hit object you willsee why, hint (use layermask)
wait I just realized what I just typed
I'll use that for Multiplayer. I'll keep that in mind. And for enemies but thanks
basically, there's probably some scoping things that make that not exactly equivalent
Yeah, I used them here
but itll apply to just the immediate statement
that's wrong lerp, fyi
Applying lerp so that it produces smooth, imperfect movement towards a target value.
sine and cosine basically already have smoothing built in, what is the extra lerp smoothing supposed to do?
its for head bobbing
that's not what i asked
I'm not entirely sure. This is the one thing I did not write
Since I couldn't figure it out myself
Where did you get it from?
yeah
With it being the wrong application of lerp too
Does it work? Like exactly as you want it to, not just a close approximate?
yep
works perfectly. there is more to it
Because if so don't worry about it for now and come back when you feel a bit more confident to figure it out on your own I'd say
yeah, I've gotten more confident fast
have you tried just using the smoothing from sin/cos instead of adding the extra lerp smoothing?
No, cause I dont know how to do that
the wrong lerp means the result will be framerate dependant
How bad would that be?
Ideally you'd want to do it in a coroutine right?\
just a geniune question
wdym. Idk what coroutine means
lerp smoothing is basically a = lerp(a, b, dt) where b is the target
you already have smoothing on b, so you could just do a = b
Players with a very high framerate would have their head bob much faster than slower framerates
what would that do? it's already running every frame
ohh
Many friends accompanying me lmao
oh ya it's working
tratio is getting printed
I mean instead of running it every frame, but I guess not since it's continuous back and forth motion and that becomes a little more complex. I like to use a coroutine if it's a one time move
honestly, currently I'm just well. lagging a lot for some reason
one thing to note though, while the tratio debug does stop printing, the infinity debug gets printed
To be honest I'm not exactly sure why it would be printing inf, inf, inf in that case
wait what do ou mean? stops printing when?
Hey, how do I make it so that I dont have to hold down interact so I can just click it instead?
the tratio stops printing when the temporary object gets destroyed, but, the (inf, inf, inf) is always getting printed
lemme send you a vid
exactly
How is it set up? What objects have what scripts?
I think I know the issue maybe
Can you add a Debug.Log(spline) line somewhere with the other debug.logs?
You don't need to use a formatted string like the others it can just be put like I wrote
Yeah
everything is printing at all times
i guess it has to...cus its part of the update()
i don't even check for whether the gameobject exists or not i guess...
Can you click the arrow next to Spline
wait what the hell
Is it not assigned?
demn it's not
It makes sense since the only time you got an error was the only time you use the Spline itself
You're taking the t value from aniSpline and using it to check something in spline
then...wouldn't evaluatetangent make a null ref error if spline is not even assigned?
Evidently not
Presumably it doesn't check if the spline exists and still tries to do math with it
It's not explained on the docs
Anyway are you able to assign it and if so does it work now? @tired python
i was told to first try to research myself, and then ask questions here...so i am still looking it up
Alright fair enough
looks like it's assigned fine? it can't be not assigned, it's serialized
it's just the default value, like ints being 0 or Vector3s being 0,0,0
the spline does exist, it just doesn't have any data
but it's prolly not the spline i am working with
if you already have a spline referenced somewhere else, why is this one serialized
sry, terminology error
i don't have it referenced somewhere else...
not a single code of mine does that...
i don't think it was tbh, you mean like it was null right?
stuff serialized by value can't be null
so what do you mean by "spline i am working with"
check out my previous images, you might understand.
this spline object that i am using, isn't a copy of the spline i made inside the scene
what's the type of spline
Spline
ok, so how did you make that spline
the one in the scene
i..drew it
is it a value in a component on some gameobject?
im referring to how it exists, rather than how you drew it
It's kind of visible in the first image here
At least it's referred to by SplineAnimate
So probably possible to get in the required script via reference to that one
(you wouldn't be getting a script, but sure)
oh wait, i skipped over the "in" lmao
mb
holy crap, i got scared, i accidentally thought i deleted the spline objects when i went to check it....i didn't realise i cut and pasted it onto another script
sooo did you find out what component holds the data of the spline you drew
Spline Container
might be SplineContainer, considering SpliteAnimate refers to it
ah yeah
so you'd need to get a reference to that container and get the spline from that
oh ya...
and SplineAnimate seems to have a reference to the container, so you could use that existing reference you have
Yeah I don't think Spline is a type that can naturally (easily) be assigned via drag and drop in the editor
then you can remove the serialized spline field, it's not doing anything (you could just make it not serialized and use it to cache the spline though)
yeah, it isn't a UnityEngine.Object, it's serialized by value rather than by reference
colour me surprised, cus that's what i initially wanted to do and i ended up deleting the spline xD
ok, i have reached my wit's end, i need your help.
so i added a Spline Container component onto my duck prefab which currently has a list of all my knots
like so
now, i am trying to get a list of these knots using this
BUT, KnotLinkCollection returns a KnotLinkCollection data type, not a Spline data type
damn my eyes are droopy
@placid jewel @naive pawn
wait a sec,i think evaluatetangent is a method of SplineContainer too
ive scoured the internet but im yet to find a soln for this. when playing looping tracks through the audiosource, there is always an audible click sound when the track loops, even when the track is seamless. anyone knows how to fix that?
Can you not just refer to the spline using the already defined one in SplineAnimate? I don't see why you're making a new spline
So you know, Spline and NativeSpline can be sampled due to the spline utility extensions
https://docs.unity3d.com/Packages/com.unity.splines@2.8/api/UnityEngine.Splines.SplineUtility.html#UnityEngine_Splines_SplineUtility_Evaluate__1___0_System_Single_Unity_Mathematics_float3__Unity_Mathematics_float3__Unity_Mathematics_float3__
and yes SplineContainer also has an evaluate function for ease of use
guys, i have encountered a problem
i swear i was just copy pasting the same spline container onto Duck and enemyAnn
Due to differing scales and positions
(inherited from parent gameobjects)
Also damn your spline is way more complex than needed, i presume you dont know about changing the in and out handles to alter curvature
was my first spline...so yeah
my pc lags whenever i try to select all of the knots
you probably only need 6 points in that spline
holy hell that's an insane spline
I'm not an audio guy so I dont know the exact technical reason, but its something about both ends of the waveform not matching perfectly. The individual samples might go from the lowest frequency to the highest frequency, so to the human ear picks up on that.
If you open the file in audacity, theres a way you can manually edit the waveform
You want to use bezier mode and then move the handles to adjust the curve
aight, i can't fix this, the temporary duck that get spawned, they spawn at a completely diff area cus the spline itself is very far.
you need to correct the scale of parents or where you position the spline
the prefab is positioned perfectly
its the damn clones that are doing this messed up thing, not only that, now, its the damn spline that moves, it's not even the duck it's the actual spline that moves

why do i need to have so many problems with my duck spawning. leave my ducks alone
There should be 1 spline and thats it
and the ducks would be spawned, connected to the spline in the scene and animated along that
What is the setup you actually have?
bruh, the duck became microscopic, it's there, you just can't see it
Doesn't answer my question
You probably aren't doing this in a smart way
When you scale objects to make em bigger/smaller it's easy to get these issues
Ideally we have a parent with 1 scale and then children we scale up/down
that's the problem, i didn't scale anything.
wait wot
Check your transforms
it's at 1
actually, nvm, my initial img is microscopic
just spent 30 mins doing nothing
not pinging, i will be resting now. just so that its easier for me to look at it.
don't cross post. and consider posting the actual code you need help with instead of expecting people to watch a tutorial to know what you are trying to do
sorry meant to delete from this channel
Hey everyone, look im pretty new to unity cause ive been working in a diff engine for years (no not unreal), and im trying to code a shader that uses my existing shader i use for triplanar materials for terrain materials, anyone know how i could achieve/go about that?
I tried coding one just using albedo, but i get
Error seems clear to me, the texture size must be incorrect for the tex array. Double check the size the array wants and what size your texture2d is.
Ask in #1391720450752516147 in future
// Apply Anti-aliasing setting
var urpAsset = GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset;
if (urpAsset != null)
{
switch (temporaryAntiAliasingMode)
{
case "off":
urpAsset.msaaSampleCount = 1;
urpAsset.antialiasing = AntialiasingMode.None;
break;
case "fxaa":
urpAsset.msaaSampleCount = 1;
urpAsset.antialiasing = AntialiasingMode.FastApproximateAntialiasing;
break;
case "taa":
urpAsset.msaaSampleCount = 1;
urpAsset.antialiasing = AntialiasingMode.TemporalAntiAliasing;
break;
case "smaa":
urpAsset.msaaSampleCount = 1;
urpAsset.antialiasing = AntialiasingMode.SubpixelMorphologicalAntiAliasing;
break;
case "msaa4x":
urpAsset.msaaSampleCount = 4;
urpAsset.antialiasing = AntialiasingMode.None;
break;
case "msaa8x":
urpAsset.msaaSampleCount = 8;
urpAsset.antialiasing = AntialiasingMode.None;
break;
}
Hello 👋
Setting up my first video settings menu and can't seem to figure out what definition to call from UniversalRenderPipelineAsset to switch on FXAA, TAA, & SMAA respectively.
Using urpAsset.antialiasing = doesn't seem to work.
Any help would be greatly appreciated. Thank you. ^^
why are you replying to a someones post from 2022 🤔
Was looking through searching for similar code to see if a solution was already in here before I sent in a question.
Maybe there is idk couldn't find it.
XD
Thank you very much. 😄
My bad I didn't find it in the documentation myself.
can anyone help me with a small issue with coding please?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
Don;t know how to fix these errors, ik it is common and easy but it's killing me!!
you have a duplicate BearData script
or you defined the class(es) twice in that file
either way - you need to find and delete the second copy
share what
just open your IDE (code editor) and search for "class BearData"
you will find two
delete one of them
{
if (groundCheck == null)
{
groundCheck = transform; // fallback
}
isGrounded = Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, groundMask);
//nearLedge =
if (currentPath == null || targetIndex >= currentPath.Count) return;
Vector2 targetPos = currentPath[targetIndex].worldPosition;
Vector2 dir = (targetPos - (Vector2)transform.position).normalized;
// If about to fall off a ledge, stop or jump
//if (isGrounded && targetPos.y <= transform.position.y)
//{
//rb.linearVelocity = new Vector2(0, rb.linearVelocity.y);
// }
// Move horizontally
rb.linearVelocity = new Vector2(dir.x * speed, rb.linearVelocity.y);
// Jump if target is higher and on ground
if (isGrounded && targetPos.y > transform.position.y + 0.5f)
{
rb.linearVelocity = new Vector2(0, jumpForce) return;
}
// Proceed to next node
if (Vector2.Distance(transform.position, targetPos) < 0.3f)
targetIndex++;
}```
any idea why this crashes my game when the character jumps?
Can you show the full script? I don't see anything in here that should crash the game
when you say "crash the game" what happens exactly?
Most likely the problem is elsewhere
{
if (target == null)
{
if (GameObject.FindWithTag("fruit") != null)
{
target = GameObject.FindWithTag("fruit").GetComponent<Transform>();
}
else if (GameObject.FindWithTag("Enemy") != null)
{
target = GameObject.FindWithTag("Enemy").GetComponent<Transform>();
}
}
if (target != null)
{
currentPath = Astarbrain.Instance.FindPath(transform.position, target.position);
targetIndex = 0;
}
}```
nothing here that would crash things either. BTW you never need .GetComponent<Transform>(), you can just write .transform
Is isGrounded a property?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
A tool for sharing your source code with the world!
Can you describe again what you mean by "crash the game"?
Does the whole program freeze and need to be shut down manually? Or something else?
Another question would be - what is Astarbrain? Is that a plugin? Or something you wrote yourself?
The path finding looks very concerning
yes, it needs to be shut down through task manager
I'd say most likely it's an issue in Astarbrain
probably when you jump it can't find a path
A tool for sharing your source code with the world!
but it isn't handling that correctly and is perhaps entering an infinite loop somewhere
astarbrain
while (openSet.Count > 0)
Yeah this is probably it
It's possible there's a bug in the code here and this loop is never terminating
To test if this is the problem can you see if commenting out InvokeRepeating(nameof(UpdatePath), 0f, updatePathInterval); for the time being stops the crashing?
though I guess it seems like your jumping is not manual
RetracePath could also be the problem
If there is a cycle in your graph
doesn't crash until the player jumps over the target
I'm going to assume jumping isn't the problem but something that's dependent on not being displaced by jumping is
right so something is probably breaking in the pathfinding when the player is in the air
It can jump until the target is below it
Try commenting the invoke repeating line out like suggested
I commented it out, player can't move anymore
Or rather, check if commenting out the Find Path statement removes the crash
character just stands there
Right, you should be able to manually place the player where you'd normally crash via Editor and attempt jumping
So it's likely #💻┃code-beginner message
It's most likely an infinite loop with your while statement
Where open set count is never less than one
Or retrace while (currentNode != startNode)
just commented out:
{
// path.Add(currentNode);
// currentNode = currentNode.parent;
}```
and it crashed as soon as the target fell below the player
well, it would, because if the while loop has no exit condition
Try limiting how often this line can runcs while (currentNode != startNode && path.Count < 1000)
If this while loop was the culprit, it should remove the crashes at the expense of not behaving how you likely want it to behave
still crashes
int iterations = 0;
while (openSet.Count > 0 && iterations++ < 10000)
{
// blah blah
}
if (iterations >= 9999) {
Debug.LogError("Too many iterations");
}``` do this too
i am sure this doesn't exist but maybe unity does have this data posted some where.
What are the most common apis used in the engine? implementing all of them in my scripting language isn't realistic but id like to make sure I get all of the popular ones.
You've got a lot of potential crashes as your looping a whole lot
What do you mean by "get" them all?
Like understand them?
you're making your own scripting language? or you would like to learn about them?
no lol i want to implement all of the most common ones in my scripting language
Sounds subjective
Generate forwarding to everything automatically.
Your language...is for a game engine? or a game?
you can also look at what bolt supports and work with that subset.
brother wtf would I be in the unity game engine discord for if I was making an engine ima just go ask chat gpt cause yall annoy me sometimes
Bolt supports almost everything, and most of it is generated
that doesn't really make sense. Unity is a game engine, not a scripting language
Sir, I asked, because I have had experience with making a scripting language parallel to C# in unity, which was basically calling C# methods via reflection.
Now, that required the entirety of unity's APIs
Do you require all of it? What is the purpose
sure it does. I am making a game that is moddable. To do this I added a scripting language so players could share mods that do not contain malicious code.
Now I am wondering if there is a list of the most commonly used apis so I can expose them to said scripting language
I see so you're looking to expose a subset of the Unity API through your modding language
Definiutely nobody has such a list
Dunno much about mods, but if you're open to pure C# as your scripting language, this might be a good lead
https://github.com/scottyboy805/dotnow-interpreter
other than perhaps Unity
So... are you like.. needing to lookup Unity's implementation of certain functions or... ?
fwiw, the answer to your original question is: it depends an what someone needs, no list exists
Appears so, I am sure unity has that data tho
A general list for all game types is probably not that useful to you anyway
start with basic types, Transform, Gameobject, Object, Vector3, Quats. And... Mathf. That should get you started....maybe
I bet it depends on the genre or camera style or other things
very true
This wouldn't really be secure from what I could tell when looking into it before chosing a different route.
Well, its not secure, but it can be made secure.
It makes little sense to approach this statistically. I believe you have to compose that list with personal understanding what’s useful and needed
i mean, where would that data come from? it's not like every type and function is phoning home
In this, you can override functions, that you feel are insecure to block them.. essentially. Example anything File.X or Application.X, and so on
there's also this, https://www.hybridclr.cn/en/
but, I just know about it, havent used it
its original function is different, but it can be used as a mod enabler
https://github.com/namazso/PawnX64
I wound up using this
its been being used since like 2002 without any security holes
That still isn't fully secure the only fully secure way to run c# since CAS was deprecated is to to run it in a separate process as a non privileged user. You can also use webassembly and can code in c# but it gets compiled to .wasm either way.
@ivory bobcat it works now
Can someone please help me with this error
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
thank you
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
@wintry quarry your suggestion stopped the crash, but it still won't move once above the goal
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
does anyone know how I would go about making parry, blocking, and attacking animations better in a 2d game (only x movement not y movement)? Would really appreciate the help.
I could not find much about it only other than people sharing there devlog, if there are any videos or something that I can use to code these mechanics knowing of them would be really helpful.
I doubt there is much, as thats fairly specific. The last game I did it in, I just used a state machine and animation controller. But im sure there are smarter ways
But if i come across anything ill ping you :D.
Thanks, and honestly I have never heard of a "state machine" I am familiar with the animation controller a fair bit now but I will check that out now thank!
damn, it actually worked out. thx a lot!
Then you have a bug in your pathfinding code
Hi there i want to make a simpel silksong type 2d game just to try and learn making games for fun but im wondering what the best way is to start because i really have no idea how to make games
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Im getting this error even though there is a variable named deathCount in basicEnemyMovement
you didnt save or you have more compile errors
thanks idk how these little things keep happening to me
gremlins in your pc messing with you
lol
Im getting an error on this line of code and I have no idea what it means, anyone know the problem?
if this is line 17 in that script it means it cannot find a gameobject with tag enemy, therefore you cannot GetComponent on a null object
but there is a gameobject named Enemy
or do prefabs not count as gameobjects
names are not tags
notice I said, Tag
also please tell me you're not running this in Update 😵💫
cache it once in start or sum
scanning every object in the hierarchy every frame is not efficient
ahh.... nooo... ofcourse not
not at all
bit rhetorical tbh. I already know lol
well if that line is running before you spawn a prefab with that you get the error
I mean you want only 1 specific Enemy? there is probably a better way to whatever it is your doing, if you explain it then its easier to suggest something
okay so I have an enemy prefab and I want the score on a piece of text to go up every time the enemy is killed
so just increase the score on the enemy death method
I made a new script to keep score, could I have just done it in teh script where the enemy dies, wouldn't like connecting the text and that script be hard
like if I keep one enemy in the scene it works
yes just connect the score with the text, why does enemy care about the text
something like
enemy
Awake(){
scoreThing = FindGameObjectByTag("Score");
Death(){
scoreThing.AddScore(1);
or even better search the component not a tag Awake(){ scoreThing = FindAnyObjectByType<ScoreScript>();
scorescript
AddScore(int amount){
score+= amount;
//update text too
i did that, but then in a different script I go, i go
scoreText.text = "Score: " + basicEnemyMovement.deathCount.ToString();
to update the score
so that I can put that count in the top corner of the screen(dont mind the assets)
that doesn't really clarify why would you track that in EnemyMovement ?
because thats where I detect if the enemy has died,(very new to unity btw, ik alot of my code looks dog)
well you're creating a very overcomplicated thing.
spaghetti af
at most you'd add the score from enemy on death into a scriptscore tracker
like i shown above
i did that i think...
no you're trying to access an int on a specific enemy
so I know how many times the enemy died, then I can give a goal of a certain amount of deaths for the player to reach
one
if I had more though would I have to change code?
well yeah you're literally searching for a specific instance
if you destroy it now you got an error until you spawn another and so on
its good to start separating these in the beginning, enemy should do enemy things not deal with tracking scores or deaths
okay this is 100% a dumb solution but what if I put an enemy prefab in the scene where the player cant reach him then freeze the enemy
I'm going to start doing that in the future
its temporary until it breaks
I would just let enemy know score/death tracker "Hey I died"
thats it
okay
if enemy dies it doesnt implode the thing searching an enemy tag , every frame especially
why is this happening, ive been trying to figure this out for like 4 hours now lol i cant figure out animating
this is a code channel..
i dont see an animation channel
you mean the one labeled #🏃┃animation
that didnt appear for me until you shared me ill post it there tho ty
you might need to enable more channels then id:browse
I've seen a lot of people use velocity over linearVelocity which one should I be using?
they're the same thing
linearVelocity is just the newer renamed version
thanks.
i figured it out myself. If anyone cares, unity doesnt recognize type metarig, had to generate the actual rig for unity
How do I get that Scratch like scripting in regular Unity that I saw in Unity Studio?
It's not available for normal Unity. The closest equivalent is Visual Scripting
Thank you
Is this a known thing where the console stops auto scrolling randomly when you have a bunch of logs spitting out in Unity 6.2.X? Or have I managed to change some setting
I meant to use Array.Exists just to check if a class is already in an array am I? That looks bit too elaborate
nvm Contains seems to be the one
List.Contains() is the better choice to see if some object is in a list
Array.Exists() does the same but uses a predicate delegate for you to customise the check
yeah thanks that's bit confusing
almost like a C# devs screwed up with naming a bit
Then best to stick with a List
Contains works with an array too it seems
Its an extension method using IEnumerable so not a perfect replacement
for speed you would want to use a list and Contains() or loop over the array yourself
again, if this confuses you stick with List
If you just want to check if an element is already in the array then Array.IndexOf(array, element) > -1. Only works if it's the exact same element and not an object with same values
that would work too but I don't get it why would contains work worse
Contains is a LINQ extension so there might be a small overhead. Not enough to care about it probably
Probably not, test the code, if it work it works. Try to run different edge cases where it might not work
My character is a first person shooter and it uses a character controller. A rigidbody cube basically attaches 5 units in front of the character.
By 'attaches', what I've done is I created a magnetic field 5 units infront of it and the cube basically tries to get to the desired point(ie 5 units in front of the character).
The logic works perfectly fine. But the movement seems slightly jittery. I suspect it is due to different update cycles?
Anyways this is the cube gameObjects logic https://paste.ofcode.org/qze5qJ6Pa2Q6uhytM5PKYF
in general I don't like the idea of keeping a gameplay state in a bunch of coroutines
character controller moves in Update while rigidbody moves at FixedUpdate
so I guess
have you turned on a rigidbody interpolation tho? might help
im making a tower defense game right now and im trying to stop the towers being able to be placed ontop of each other. Right now whats happening is that it will place but if it ever comes close to an invalid spot, that tower will never be able to be placed.
{
if (!spawned.gameObject.GetComponent<TowerBehaviour>().isInvalid)
{
spawned.gameObject.GetComponent<TowerBehaviour>().isPlaced = true;
spawned.gameObject.GetComponent<TowerBehaviour>().isInvalid = false;
spawned = null;
}
}```
something seems to be happening here as if i release the mouse button then it cant be placed
Couple points that I can see by quick readthrough:
yield return new WaitForSeconds(0.05f);
yield return new WaitForSeconds(1);
```The two lines above don't seem particularly useful. Is there a reason not to just wait 1.05 seconds once to begin with?
You are using GetComponent quite extensively. It is not inherently bad but in this case I would think getting the two text elements once in `Start` (store them in variables) would be better for both readability and performance. Whether the code logic actually works I cannot comment on really since I don't know what it is supposed to do.
throw new InvalidOperationException("Insufficient Gold!");```
invalid op wont show as an error on terminal?
I hope you are not using that for gameplay but only as an internal sanity check or something
this line of code making me chuckle
I am not having a solid grasp on that but if you throw an exception that's a damn error and it's not meant to happen and it will get shown in console likely
Can anybody look into this please 
its an sanity check, i have a custom logger that will pop UI windows out
yeah it works just fine
what the he...bro
@compact roost
Don't ping people for no reason
for (int i = 0; i < roomSpawns.Length; i++)
{
GameObject[] currentWaveSpawns = new GameObject[10];
for(int j = 0; j < roomSpawns[i].transform.childCount; j++)
{
Transform currentChild = roomSpawns[i].transform.GetChild(j);
if(currentChild.gameObject.tag == nestSpawnTag)
{
_nestSpawnPoints.Append<GameObject>(currentChild.gameObject);
}
if(currentChild.tag == antWaveSpawnTag)
{
currentWaveSpawns.Append<GameObject>(currentChild.gameObject);
}
}
_antWaveSpawns.Append(currentWaveSpawns);
}
im trying to get children based on their tags but for some reason both the ways to get their tag return untagged while they should be tagged. (nothing here is null)
First mistake is using tags
If you had a custom component you could just GetComponentsInChildren()
Also what type is _nestSpawnPoints
I applaud you for using superior for loops
I don't see why you'd use Append instead of a list + add
c++ programmer :)
im quite new to unity itself so i did know of add before
Wait till you hear what accessing tag does then
they're just gameobjects
It will allocate a new managed string each access
oh god
CompareTag() exists for this reason
yeah lol why the hell does that work like that?
Because the tag value is stored native side so a managed string copy needs to be created when you access it in c#
No its just how it works
damn alr
native <-> managed crossover has its challenges
but anyways, do i add like an empty component to each of the children and use that as identification?
I would and the moment you wish to add some data to store you already have a component!
yeah i get that too, but if you create something that has such behaviour that people usually dont expect, its objectively not very viable...
You can alternatively have a component on each roomSpawn, and that component would store a list of the child transforms you want
appreciated
This way you get only 1 extra component
Its fine because past the beginner stage you basically never touch tags again
alright. Ty guys
well yeah thats fair, but assuming tags were meant to be used bast biginner (which i think they meant to make them for that too), then they done fucked up
also, what is your alternative @grand snow ?
Components always
you TryGetComponenet?
also, @compact sandal let me poison you for a sec... but here are 2 falid ways of nesting for loops:
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
for (int k = 0; k < length; k++) {
for (int l = 0; l < length; l++) {
}
}
}
}
for (int i = 0; i < length; i++) {
for (int ii = 0; ii < length; ii++) {
for (int iii = 0; iii < length; iii++) {
for (int iv = 0; iv < length; iv++) {
}
}
}
}

0_o.... poison was effective
hehehe
if i have a component from a gameobject, how do i get its object?
NestSpawnPoint currentNest = GetComponentInChildren<NestSpawnPoint>();
_nestSpawnPoints = currentNest.gameObject;
this doesnt seem to work
this is the error it gives me
sorry, shouldve been clearer
the .gameObject does work
it's giving a GameObject
the assignment doesn't, because _nestSpawnPoints is a GameObject[]
im still actually curiosue how you apply this, its pretty relevant for me currently as im on a problem involving tags and wanna see if your way would be viable for me to also implement
You either pre assign the objects via some Serialized list/array or as i said, have a component on each child object
Then you already have access to them all or can locate them easier
fair enough, so its basically just a custom system
Everything we do is custom
would it actually just be faster to make a manager for this and put references of types of objects in seperate lists in that manager?
cuz that does seem really easy to make
Thats like asking if its better to write code to make something work (ANSWER IS YES)
so if I have like a thousand npcs that are all going to try to update a variable in a different script, what would be the best way to do that?
right now I just have them all doing it but that doesn't seem super efficient
lol fair, but im asking as apposed to using unity's default tags and .CompareTag optimization wise
theoretically
i was wondering if you would use something like a mutex?
alright, so how would i go about knowing if a player collided with a wall or with ground?
only needed if using threading which I doubt you are
A monobehaviour that responds to physics events and forwards this event to somewhere else
how tf would a tag be sufficient here anyway
The only performant solution for having many thousands of entities is to use ECS
well its the basic tutorial way of explaining how to handle on collision detection:
void OnCollisionEnter(Collider other) {
if (other.CompareTag("Wall"))
}
but i do despretaly want to get out of that system as its wierd and annopying
Id use layers here instead
like, im way past the point of hardcoding yet this is still hardcoding
or you try get component.
If the detection is done the other side (by the wall) then a monobehaviour for that makes sense
any idea where to find good tutorials for using that?
hello
thats fair, i been using those more lately and am liking them.
though, im still currently targeting layers by getting the mask with the string names of the layers, i assume there is a better less hardcoded way to do this?
i was thinking to just make a constents script where i define the layers i have but there must be a way to just fetch it from unity right?
If you are not very comfortable with c# it may be tricky to learn and use but its the best and most performant way to handle and manage many instances of an object
https://docs.unity3d.com/Packages/com.unity.entities@1.4/manual/index.html
Or use a serialized layer mask
helo
helo
you can also check for the component directly or check for interfaces
if (TryGetComponent(out IFoo foo))
Debug.Log(foo);
maybe he just wants to be greeted
/j
yeah true, thats what i been doing more so, but thats not a very good system if its more dynamic though
like you collide with any object, and the object can be many different things where x can have all different components of y
Then perhaps a common component that has this data in it?
As soon as an idea goes past "is this thing x" you realise tags no longer work
true
thats where im at for a while now but im also trying to do less custom stuff as im super good at over engineering stuff that doesnt need it
That's essentially what interfaces are for . . .
mhh, ive never used an interface in c# before and dont really understand what they are used for overall...
because c# cannot do multi inheritance we can use interfaces instead
public class Door : MonoBehaviour, IInteractable
^ Now my door can implement the interface and keep its current base class
oh shit right, i know what interfaces are and used them, i just completely forgot about them...
You can check for shared functionality between unrelated objects . . .
public interface IAttack
{
public void Attack();
}
public class Gun : IAttack
{
public void Attack()
{
Shoot();
}
public void Shoot() { }
}
public class Rock : IAttack
{
public void Attack()
{
Throw();
}
public void Throw() { }
}
public class Sword : IAttack
{
public void Attack() { }
}```
also, anything that lets me use less of c# inheritance is good cuz im super done with abstracting more and making everything more complicated for no benefit...
so its like an abstract class but without the chance of predefining an virtual method that already contains functionality?
@grand snow From the unity badge of sleep John Kho ferri Bekam
no, yes derp. abstract classes cannot be instantiated. Abstract members MUST be implemented by super classes. Virtual members can be optionally overwritten
Yes, since an abstract base class must be inherited. This avoids the hierarchical issue . . .
that doesnt quite click for me yet, but in the back of my head that does sound better and less complicated so i guess its time for me to dive back into some research
yea i realised 😆
interfaces are a bit more general than abstract classes, if you want to think that way
nowadays you can provide default implementations for interfaces too, so even in that sense they're not that different
Its a contract that states "if you implement me, you need to provide x,y and z"
"i dont care how but you have to!"
super classes are different, its a way to extend a class and inherit functionality (and optionally override bits)
im also at that point of programming that im trying to learn more why things are used over other things, and honestly its a lot of fun but takes so much more time while programming as i need to stop and research the basics again but deeper this time...
like struct vs class and which one to use in what situation. learning that was really nice actually and i could apply it right away as there is now a clear reason why you should use one over the other.
more general as in, if you have a struct, such as Vector3, it can implement interfaces, but it cannot inherit from any base class
ah right, so they are pretty identical to how golang does them, just a list of fields and methods that the class that inherits it will be required to hold and now you can relay on the fields being present at all times.
!warn 1397008166843191467 Don't spam on the server. Read #📖┃code-of-conduct
@raman842 warned
Reason: Don't spam on the server. Read #📖┃code-of-conduct
Duration: Permanent
Yea and the fact that a class/struct can implement as many interfaces as you want makes them great for situations where you just want a common function or property.
IInteractable -> bool Interact()
IDamagable -> void Damage(float damage);
damn yeah that sounds like some good code security where you can write a lot of things tht are reused all over all the time
wait, can fields also be specified by interfaces?
instead of a method
no, but properties can
no only properties and methods
properties are just fancy getter and setter methods anyway
what do you mean by properties?
so in reality its just methods 😆
oh right
fair, so then you can just make a field that is actually a property that is just a getter but then the class has to create the thing that is fetched?
thats a bit confusing, so that must be wrong
Maybe i confused you
no your fine thats likely my own doing
yeah no i know what properties are
and fair, i did kinda forget you dont have to specify what get gets
so yeah then they can be used as fields
you only ever need to if you are adding logic to either the getter or setter
-# until we get C# 14 support with the nice field keyword
which means, if we try tying it back to that unity tag system problem, i can make an interface like so:
public interface ITag {
public string Tag {get; private set;}
}
but thats dumb tho
but it could work
The secret truth is that properties are very much like methods under the hood
interfaces only define public members, so you can remove the modifier public modifier and leave the private set; part to the implementation
oh yeah exactly
oh interesting
but that example misses the point a bit, with interfaces you can have much more than tags
you have type safety and can declare specific functionality for each type
tags are a failed concept
oh yeah i know, it was just me trying to tie it back to the previous topic we discussed
but its def not something i would actually do
the idea around them were supposed to be editor friendly way to organize these objects but it even fails at that
yeah we had this discussion a little up already but yeah thats a good sum up of what was said
godot has an interesting concept called groups where you can tag specific objects that all can have similar method calls, so it presents this interface idea onto the editor level, however they aren't type safe as the nature of its language
Hey, I do have 2 videos about interfaces if you want. With theory and practical use cases in Unity. Will that be helfpul?
oof
oh yes please, send them over
Here's an explanation:
https://www.youtube.com/watch?v=DWj_mPUtuqw
then here is one more example:
https://www.youtube.com/watch?v=zBD4r9UxLpQ
and then if you would rather use that in 3d game, here's a video:
https://www.youtube.com/watch?v=cx9y5TV3TS0
In this unity tutorial we will explore the C# interfaces. We will do it on a practical example - we'll create objects that react to player shot. Your scripting will jump on to new level!
In this series we will cover a lot of useful concepts. This and few other episodes will be fully dedicated to interfaces as I noticed this is one of the subjec...
Learn how to create openable door, containers with loot and message spawning elements practicing usage of INTERFACES! This is second episode in the scripting series and it builds on top of theory we discussed previously (over here: https://www.youtube.com/watch?v=DWj_mPUtuqw).
There is quite a lot of interesting elements in this tutorial:
- B...
In this FPS/Horror episode we'll create a customizable and extendable interaction system. We'll create a button and a toggle, however in the future we'll create also other types of interactions!
You will learn:
- How to detect what object is under the crosshair
- How to make interactable button
- How to make interactable toggle
Let me know if that is what you were looking for :)
huge, ill def check these out
the funny thing is, the first video actually explains a problem that we were also discussing about how to replace tags efficiently, so very on topic.
Yay! Happy to hear that :D
wait, can you check if a class inherits an interface?
They're useful for composition that's for sure. Usually you can get away with some abstraction
you can check if a class derives from anything
lol watsup @sour fulcrum
if (MyBehaviour is IExampleInterface)
eg.
The one problem with interfaces with unity is that you can't serialize by them which does make abstract classes a bit more appealing
well fair, its only methods right
also cant you just semi serialize them by create private copies of fields for important values?
the instance of the interface itself is what you'd want to be serialized
eg. a list of IEnemy
The problem is you can't specify the type when trying to serialize by the interface on the editor. There needs to be some extended option for the editor but Unity hasn't implemented a way for that. You'd have to make a custom drawer using serialized references
going with this example, would i be able to make a list<IEnemy> and then populate the list with class A : IEnemy but also add class B : IEnemy in the same list?
in c# yes, in unity inspector no, because no interface serialization
You can however declare as an abstract type and present a more derived (non-abstract) object into these fields on the editor
oof right...
yeah its like always with c#
a good thing but with a catch that is solved by another good thing, and now you got to think of why you would use one over the other before writing it out...
interfaces pop up way more often if you were doing just straight c# since unity's component system tends to solve a lot of problems you'd otherwise look at interfaces for
interfaces are easy to append to existing classes, while abstraction you are modifying the root which can change the behaviour of alll of these derived classes
yeah exactly, which is another thing to always consider, what unity does with the code you write
Yeah, this is a thing I miss the most. It would be so awesome to have interfaces in the inspector and then e.g. just select a type and have it instantiated at a runtime. I think you can do that with Odin
usually you want to strive for composition as much as possible. You can dig yourself a hole pretty easily with abstracting everything as is the nature of OOP really
yeah i think odin does that, i can actually try it rn to test it out
Yeah, I've yet to really play around with Odin but they've a bunch of things that you expect Unity would have natively
they should really buy them out, but seems like they've some partnership as of recent
some of odin gets abit weird tho tbf
like iirc they just say "dont use serialized dictionaries in prefabs"
Yeah, I am afraid of using this type of complex assets. Even though I like it, I feel like writing my own editor script is much easier and stable long term.
Because as you say there is always this one thing that doesn't work and you are always wondering - is it you or the asset
I really like odin for the simpler stuff they have, but yeah there is some weird stuff that sometimes comes with it... but overall its ability to orginize the inspector for each component a bit more efficiently is super nice
@forest wolf @sour fulcrum @timber tide
here is a good example of that:
its not a whole lot different from what unity can usually do, but its enough to not fully cover the whole inspector with a lot of fields that just usually dont apply for that situation
Cinemachine package. Player Index is that for local play? if there are multiple player like coop games? if im doign networking can i just ignore it?
Do you mean this from InputSystem? https://docs.unity3d.com/Packages/com.unity.inputsystem@1.15/manual/PlayerInput.html
this on the cinemachine
that says PlayerIndex
and it should be referring to local players
how do you get the length of a list in unity?
for some reason can't find it online
oh nvm, its count
Lists don't have length because they are not fixed size
When it comes to Odin its license scares me a littl bit 🤣
.Count :) - this will get you the current number of items in the list (actually number of allocated items, because you can have nulls there, but you get the idea :D)
thats fair, i did not have to worry about that so far yet
Bloody hell, sorry! I wrote .size(), I am using different language at work haha! I fixed the message to show the correct property :D
just FYI, nav was explaining why List uses Count rather than Length like arrays use
Hah, sorry! I missed the point!
Yes! I did! It was tough 48h :D - my entry is called La Maestra.
I need to disappear for a moment, I will be back in a while! See you soon guys! :D
yeah see, you have what is called post jam brain, and you are excused. alsi am in the same boat and i will be checking out your game and rating it soon :3
Hi guys!
I've faced this problem a few minutes ago
The part of code was like this
And I solved it like this. Was this a decent solution?
what is the problem?
I mean there's no glitch existing now, so, is it maybe decent?
It must jump simaltuneously, but it stops when I press Space
why not keep the original horizontal velocity? why overwrite it with half the jump height?
Apparently the speed is being turned to 0
I tried to, but it still "hinders" at the moment of the jump
well yes, you were explicitly setting it to 0 in the first snippet
show how you tried that
Okay 👍 Let me
also, you should be using and else if instead of the second if statement i think
or just not using a separate if statement at all and using math to do the sign check
true
now show the code
i still dont really know what i mlooking at
It "hinders" when jumps, but it mustn't stop
so before we help you with your code, how long have you been programming in unity for total?
i said use its velocity, not the input
What's wrong with this? Looks fine
thats good to know, ill adjust my answers based on that
When it jumps,x axis is being altered to 1, which stops the initial speed the object had before he jumps
oh I was looking at the vertical
Sorry? 😅
yeah i mean, just don't set it to 1
btw are you aware that Rigidbody2D has .linearVelocityY; which you can modify directly to completely avoid touching the x
Let me try that
PlayerRigid.linearVelocityY = Jumpheight;
instead of using HorizontalAxis there, use the existing velocity there. or assign only the Y axis. or add force like you're doing for movement anyway
(JumpHeight isn't a good name for that variable imo)
Thank you so much 🙂 It works well now. But isn't it better for me to comprehend the situation of this I can handle to become a better scriptwriter?
Also worth to mention that you really dont want to do a rigidbody.AddForce call inside Update()
isntead, that line should be inside a FixedUpdate() method as rigidbody.AddForce is a physics calculation and those should only happen in FixedUpdate.
Okay, I will read about those. Thank you for help guys 👍 I appreciate it
yes you should understand the situation
doesn't really sound like a code question
is your camera perhaps not getting cleared? i don't know if that affects things in the UI, but that's one of the few things I think it could be. you'd have to show the inspector for your camera if you are unsure
Ah sorry, I'm only seeing unity-talk and code-beginner channels, is there a better one to ask this? Here is my Camera Inspector.
id:browse to see all channels and their descriptions.
also are you rendering your UI to a render texture by any chance?
I posted my question in Rendering/2D, thanks again 🙂
I wrote the following coroutine to toggle a door. For some reason it only works when the door is alligned along the x axis and not when its alligned along the z axis.
private IEnumerator ToggleDoor(float dot)
{
Quaternion targetRotation = _closedRotation;
if(!_isOpen)
{
if(dot < 0)
{
targetRotation = Quaternion.Euler(new Vector3(0, _closedRotation.y - _openAngle, 0));
}
else
{
targetRotation = Quaternion.Euler(new Vector3(0, _closedRotation.y + _openAngle, 0));
}
}
_isOpen = !_isOpen;
while (Quaternion.Angle(transform.rotation, targetRotation) > 0.01f)
{
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime * _openSpeed);
yield return null;
}
transform.rotation = targetRotation;
}
multiple failure points here, check your values esp the dot.. and that lerp is also not written properly
also 👇
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
how exactly is the lerp wrong then?
https://unity.huh.how/lerp/wrong-lerp
almost though if you look at this example
https://unity.huh.how/lerp/coroutines
Applying lerp so that it produces smooth, imperfect movement towards a target value.
fixing the lerp didn't help
It's just weird that it works perfectly on some doors and doesnt on others$
I never said the lerp would fix it, i just said you wrote it wrong
alr
you need to check those values you're passing through
you'd need to show more like _closedRotation what values etc
you probably want to be assigning to the local rotation rather than the object's global rotation (assuming the object has a parent that it can pivot around)
otherwise you need to make sure that _closedRotation is the actual target world rotation (accounting for any extra rotation for the object at rest)
[SerializeField]
private float _openAngle = 90f;
[SerializeField]
private float _openSpeed = 2f;
private bool _isOpen = false;
private Quaternion _closedRotation;
private Coroutine _currentCoroutine;
public bool IsOpen
{
get { return _isOpen; }
}
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
_closedRotation = Quaternion.identity;
}
public void Toggle(Vector3 pos)
{
if (_currentCoroutine != null)
{
StopCoroutine(_currentCoroutine);
}
float dot = Vector3.Dot(transform.forward, pos - transform.position);
_currentCoroutine = StartCoroutine(ToggleDoor(dot));
}
private IEnumerator ToggleDoor(float dot)
{
Quaternion targetRotation = _closedRotation;
if(!_isOpen)
{
if(dot < 0)
{
targetRotation = Quaternion.Euler(new Vector3(0, _closedRotation.y - _openAngle, 0));
}
else
{
targetRotation = Quaternion.Euler(new Vector3(0, _closedRotation.y + _openAngle, 0));
}
}
_isOpen = !_isOpen;
while (Quaternion.Angle(transform.rotation, targetRotation) > 0.01f)
{
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime * _openSpeed);
yield return null;
}
transform.rotation = targetRotation;
}
oh this looks better
put cs after the 3 ` and it'll look even better
oh no you're mixing quaternion and v3
like _closedRotation.y - _openAngle doesn't make sense
How do I fix this "setbool" error"?
what are you trying to SetBool() on? apparently it doesn't exist
also
!vscode
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
these are the bools, I even copied and pasted the name to make sure I spelled them both right
that doesn't answer what I asked
what are you trying to SetBool() on?
as far as the computer knows, you want to call a method SetBool(). Apparently it doesn't exist
got it thanks
~~https://paste.mod.gg/~~ (link below)
I've been trying to fix this for 45 minutes now, I'm at my whit's end. It just doesn't make any sense.
For some reason, my controller inputs work completely fine. However, my mouse inputs...just don't? You can see from the 4 debug messages that no inputs are being detected when I try using the mouse (Rotation Input is always 0). Anyone have any ideas?
the link is the homepage 
yes you must save to generate the link
Thanks
FirstPersonController: https://paste.mod.gg/yyhcpjxbwfxh/0
A tool for sharing your source code with the world!
Player Controller: https://paste.mod.gg/pxwcabuoijjb/0
A tool for sharing your source code with the world!
As far as I can tell, there's nothing different about how these are handled, I have no idea how one can work while the other doesn't
OMG
I FUCKING SOLVED IT ARE YOU SERIOUS
So uh
Turns out when you enable Keypad
It doesn't automatically enable the mouse 😆
And so even though Delta(Mouse) was under Keyboard&Mouse
I still had to explicitly say you can use a mouse :P
Welp
Exactly how close does Mathf.Approximately have to be in order to register as true? Because I was expecting it to consider 2.291054E-07 and 0 close enough and they're apparently not
Documentation says that it uses Mathf.Epsilon
As in the difference between them has to be Mathf.Epsilon?
Because I feel like I've gotten a positive value with a bigger margin of error than that before
Wdym by this?
I mean I feel like I've gotten it to return true when there was a bigger difference between the two numbers than that
Was trying to link that but github search is not working for me 🙃
And this should still account for any floating point inaccuracies sufficiently, right?
Because for some reason it's not for me
"any" inaccuracies? no
it will account for such inaccuracies within that range they define
It is sort of adaptive, so the epsilon depends on the magnitude of the input numbers
public static volatile float FloatMinNormal = 1.17549435E-38f;
Definitely smaller than your e-07 number
I mean inaccuracies that should just naturally arise from floating point. If a difference is greater than that value then I should be assuming it's the result of something else, right?
No, there's no way to guarantee that in general
Especially since it's easy for such inacurracies to compound over repeated calculations
there is no limit to how large your floating point error can be
It is also different depending on the magnitude of the numbers involved in the calculations
Yeah, the precision errors can also accumulate
This is what I have
if (Physics.Raycast(rb.position + Vector3.up * SKIN, Vector3.down, out RaycastHit metaHit, groundingMask) && Mathf.Approximately(metaHit.distance - SKIN, castLength))
{ grounded = true; }
else { grounded = false; }
if (!grounded) { print((metaHit.distance - SKIN).ToString() + ", " + castLength); }```