#๐ปโcode-beginner
1 messages ยท Page 483 of 1
did you add the attribute? [CreateAssetMenu]
yes
ok save the script, go to your assets folder
actually one exception , dont store anything that changes in SO
always make a copy from the default in SO and modify that
should be the top button
does a list of buttons popup? maybe your right clicking wrong area
thats a my class
can you screenshot
makes it easier to see what im looking at
because maybe your just in some random place also, which can be confusing
try creating it with the menu properly labeled
[CreateAssetMenu(fileName ="WeaponSO", menuName ="Weapons/WeaponSO")]
yes, then there should be a button for SO (if you named your script that)
yeah you can do this, but its not a requirement @queen adder
not there
hold on
i get the issue
my script didnt save the name inside the actual script
but did on the outside
also make sure you dont have compile errors
yeah did it
ok so can you see the SO now?
yeah
ok create it
name it anything, M4A1 or whatever you want
change the values of the variables
uh why
so you can store your gun data?
since theyre from the logic script that ive been using theyre perfect as is
huh
you mean this?
yeah
why would i change them-
wait
no
dont change the values on your script, but on the new SO you created (should be blue in the assets folder)
you make one for each weapon
on side note - these should probably be in a struct that you can copy btw if you plan on modifying any of the values at runtime
(changing 1 so changes all the SOs of that instance)
if you have pistol that changes then if you get another Pistol it has the same stats
I suggest you head to !learn first, you seem to lack the knowledge on how all of this works
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
yeah just dont worry about it for now
man fuuuuck thaaaaat i hate mindlessly watching tutorials
this is how i like to learn
for example ammo should probably not be in SO only maxAmmo
so you can store ammo inside weapon.cs instance itself
Start()
currentAmmo = weaponSO.maxAmmo
@queen adder Make a thread, and do so in the future if you're spending more than 5 minutes on a question.
You're excuse that you need someone to explain things to you in order to learn is not going to fly here.
But since you're insisting, use a thread so you're not flooding this channel yet again.
Hi guys, I am learning C# for Unity. Do you guys have resources like YT clips about things such as code efficiently, function to be aware of, handle events,..? Thank you very much ๐
Unity has it's own !learn series
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
I tried doing this but no luck ๐ฆ
transform.forward = Vector3.Lerp(transform.forward, Arrow.GetComponent<Rigidbody>().velocity.normalized, Time.deltaTime);
That use of lerp is wrong, though I'd just use this https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
Also cache that GetComponent call
GameObject Arrow = Instantiate(projectile, transform.position, transform.rotation);
Arrow.GetComponent<Rigidbody>().AddForce(Arrow.transform.forward * launchVelocity, ForceMode.Force);
Arrow.GetComponent<Rigidbody>().AddTorque(Arrow.transform.forward * torquex * torquey, ForceMode.Force);
So for this example I would do it for transform.rotation?
transform,rotation = Vector3.RotateTowards(~~~);
Instantiate a Rigidbody instead of a GameObject to avoid GetComponent
maybe little dumb question - i realized i really need to backup my game project, i have account on Github. do i need to do a new project and import things there or i can commit already existing project to new repository ?
I think I tried that but the thing it's instantiating doesn't have a rigidbody and it was looking for that for some reason
it does have a Rigidbody
otherwise your GetComponent will fail
look up a video on Youtube
the one i checked he only showed with new created project
that's where my questions comes from basically
You can commit your existing project to a new repository
Just make sure you add an appropriate .gitignore file first
Weird problem but the rigidbody has a gameobject before editor start but it disappears on start
Before editor start
After
Yes, and again at least cache that rigidbody or instantiate it from the rigidbody instead of the type GameObject.
Also this makes it look like the code is only running once. This is something you'll have to do in update or fixed update
The rotation part* would have to be in update or fixedupdate
Rigidbody Arrow = Instantiate(projectile, transform.position, transform.rotation);
Arrow.GetComponent<Rigidbody>().AddForce(transform.forward * launchVelocity, ForceMode.Force);
Arrow.GetComponent<Rigidbody>().AddTorque(transform.forward * torquex * torquey, ForceMode.Force);
It's a rigidbody now
I put it in a function that is called by update()
If it's a rigidbody now, then you dont need to GetComponent rigidbody still..
Also I have no idea where that torquex or torquey came from. Is this from AI or some tutorial, because this is quite questionable.
If you want it to just rotate towards where its moving, take the original code you had with lerp and just change that to MoveTowards as I suggested way above
The torque was something I was experimenting with, it actually makes the arrow roll so I kept it ๐
thank you
Oops I meant RotateTowards but still that torque does look questionable. Im assuming those numbers are both floats, so this isnt like an X or Y axis, it's just multiplying the forward twice
It was also some experimentation but I realized it doesn't do anything more when changing the values
The torque does shake the fletching a bit recklessly though
I'l do the rotatetowards part now though
I can't just substitute it in for transform.forward, looks like I have to make a variable with it
Which is weird because in the documentation they did
Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f);
and i'm not able to do that
what's stopping you
No idea
Are you using the correct Vector3 class?
Are you sure you didn't do using System.Numerics; or something?
Or perhaps made your own Vector3 class
Both Vector3 classes come up with numerics
Yeah because you did what I mentioned
so confused. I was able to use vector2 throughout the other State scripts but not this one
Delete using System.Numerics; from your code @lethal elbow
You need using UnityEngine;
When it says "Are you missing a using directive" that's what it's talking about
wow what are the chances some1 needs to delete that and someone needs to add that
very high
the cleanup code must have deleted that, thanks
because beginners stumble over namespace stuff constantly
true
I see the issue now
using Vector3 = System.Numerics.Vector3;
Deleted ๐
Does System.Numerics have a Vector2 struct?
Ok just read the whole convo
I was confused with this
float singleStep = angularSpeed * Time.deltaTime;
Rigidbody Arrow = Instantiate(projectile, transform.position, transform.rotation);
transform.forward = Vector3.RotateTowards(Arrow.transform.forward, Arrow.velocity.normalized, singleStep, 0.0f);
Arrow.AddForce(transform.forward * launchVelocity, ForceMode.Force);
Arrow.AddTorque(transform.forward * torque, ForceMode.Force);
No rotation so far ๐ฆ
You would need to be doing this in Update or FixedUpdate on the arrow itself
it's not something you do when you spawn it
Ah, so a new script
Arrow.cs
Excuse the no formatting but something just like this?
public class Arrow : MonoBehaviour
{
[SerializeField] Rigidbody rb;
bool launched = false;
public void Launch()
{
launched = true;
}
private void FixedUpdate()
{
if (!launched) return;
float singleStep = angularSpeed * Time.deltaTime;
transform.forward = Vector3.RotateTowards(rb.transform.forward, rb.velocity.normalized, singleStep, 0.0f);
rb.AddForce(transform.forward * launchVelocity, ForceMode.Force);
rb.AddTorque(transform.forward * torque, ForceMode.Force);
}
}```
```cs
void Launch()
{
Arrow arrow = Instantiate(projectile, transform.position, transform.rotation);
arrow.Launch();
}``` IG
I'l use your one because what I did gave my arrow the funkiest curve to it :p
Just saying I did mention this above as well, to put the rotation part in update or fixedupdate at least. #๐ปโcode-beginner message
But yes some script should be on your arrow controlling its rotation
And you shouldnt be using AddTorque if you wanna just directly set its rotation. Or use AddTorque (look at the docs for the values to use) and dont set the rotation
Choose one or the other
I just copied yours and shown example where to put it ๐
The rotation part was in a function that was called by update
idk its fixed now anyway
I'm not sure what's going on with the launch function but Arrow isn't a class right?
yess public class Arrow :
thats literally a class
Launch is probably not needed but just an example to tell your bullet to star doing something after spawning it.. totally uneccessary if its already in fixedupdate tho
its good to see examples of how you can call methods like that though
The arrow is doing a weird curve but it's late so il return tomorrow, thanks for the help so far. I'l leave you all with a video of it
Is there a way to drag into an EditorWindow script a .cs file?
TextAsset maybe ?
cs files as just text files no?
MonoScript should be the type, if I remember correctly
interesting.. TIL
inherits from TextAsset, very nicee
ig both work, Mono better if you need specific functions n stuff relating to Mono scripts
neat
(this is why you see "MonoScript" when you incorrectly try to reference a script instance on a UnityEvent - it's literally the type Unity uses to represent script files)
oh yeah lol that makes sense i recall you can only rename or something
does anyone have a suggested tutorial for learning to do inventory systems?
im not sure how making inventories usually goes
id assume arrays are a big part of it so learn about those
i love giving advice id never use myself
but yes the most basic inventory would indeed use an array or list..then you can do more complex ones like dictionaries
Design it on paper first: how exactly do you want it to work from the user perspective?
Then break it down into smaller tasks and move on to implementing/researching each one.
That's the universal solution for any mechanic btw.
i feel like i gotta yank a chunk out of my code because i originally designed it where you just picked up one item at a time
but now its not being simply picked up and held, but to my memory the object would be getting destroyed and its data stored
i guess i can keep most of the functions attached, but just would need to delete any place where its actually used
just gotta add that to a new script yipee
Yanking a chunk of code is normal. Though, maybe keep it as an obsolete code. You might need to reference it later.
soon it will get to be reused ๐
i cant work on this today. i was so excited because i had finished and mostly fixed the pick up and dropping scripts, and how to get items working when you have them equipped, except for a slight problem with clipping objects, and I've just been working on this without a tutorial, and I fixed one of my bugs.
but now the mood is just ruined knowing that i worked on something that cant really be put to use for quite some time until i get the inventory situation handled
hey so i was reading something about doubles and i was wondering should i be using doubles instead of floats?
do you have a reason to use doubles
not really but the thing i read said the only difference is doubles can hold 2 times the size floats can
well, unless you're doing stuff like clicker games, there's very little reason for them as you can't even use them with the majority of Unity's API calls
ok
there isn't a Vector3Double class
And that they, by definition, take up twice the space
Is there really any noticeable difference between 0.0001999 and 0.0002? Do you have anything so precise that the difference between them is going to matter?
Which template should I use for 2D games?
either of them, universal just has better lighting than built in pipeline
hi, im having problems with this code, can anywone find a solution?
whats the error
K thanks
line 21
i can see that, im asking WHAT the actual error is
screenshot the Unity console
im following a tutorial for some ai but the tutorial dosent have red lines
im asking what the error is dude
just show the console in Unity or hover of the red line
since you passed a float as the parameter for Random.Range it is returning a float. you cannot assign a float to an int variable without casting which the error message says
perhaps they have different variable type in the tutorial
this is a screenshot from the tutorial
doesn't look like they are using a configured editor
oh
yeah
bad tutorial
doesnt have capital in class name either, probably not some great tutorial
everyone will have different logic
just look up one for basic AI
ok
and then try to adapt it for your needs
ok thx
first time I've seen someone use x to share code 
Did I make any mistakes here?
https://hastebin.com/share/zukulewuhe.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Doh!
That's... the channel we're in.
NM
Dw, happens to the best of us lol
Your StopAllCoroutines(); call doesn't do anything
๐คทโโ๏ธ does it do what you want? you probably dont need to call StopAllCoroutines(); but otherwise theres not much code to go off here
How do I stop the coroutine then?
you don't need to
it stops when all the code is done running
(like any other function)
Are you under the impression this is going to keep repeatedly spawning stuff?
if so, then yes you have indeed made a mistake
Oh wait I need a While(true) lol
and if you want to exit from the while loop you can use break;
Thx!
or you can directly exit out of the whole coroutine with yield break;
I only recently figured out that I can actually learn C# without being annoying lol
Like when I tried learning it the first time I was so caught up on learning what IEnumerator meant exactly instead of just using it because I understood how to XD
yeah - that's a common pitfall - trying to understand the meaning of every word you see
it's counterproductive
You can circle back later on when you have a better understanding
(While I have been managing to learn C# pretty well recently, I'm not confident enough to rely on it lol- i'll keep using visual scripting for main game logic for now)
As long as you keep in mind the speed of visualscripting being behind raw c#, you are good to go with visual scripting.
Um... Is this normal??
Yes, its telling you, that there is a random version from system and from unityengine scope.
Why's this suddenly a problem?
There we go :3
maybe you are "using" System inside your class and so unity does not know what to choose from
because you have both using System and using UnityEngine in your code
Considering using System; is grayed out in this screenshot, why not just remove that line? You're not using it anyway.
If you are using it, then this is the correct way to omit the exception.
Guys whats Gizmo in Unity?
not a code question and please do not cross post
dont u use it in coding tho?
you can do
If you want to use it in coding, you should know what it is.
thats why im asking
Did you try googling or looking in the manual?
i tried googling
Point is, you're supposed to now about it before you even get to coding.
but i got something sicentific
"What is Gizmo in Unity"
so dificult
So you checked these pages and still don't understand?
We don't. We're just trying teach you how to solve issues.
What part did you not understand then? The manual pretty much tells you "Gizmos are blablabla".
And even shows some screenshots with examples.
what does it mean when it says setup aids in the scene view?
also whats the difference when u type it with selected and one without it
Quote the whole sentence.
"Gizmos are used to give visual debugging or setup aids in the Scene view"
Selected what?
There's nothing technical about that sentence. It basically means that gizmos help you with setting up your scene/gameObjects/components.
Selected would only show when the object is selected obviously.
so it would update constantly without it being selected?
Yes.
oh great thanks
how to get the i value which i initialized in g() method in interface?.
i have range but its saying i dont, I dont get it
try ((interfaceimpl)this).g();
(Didn't know where else to ask, sorry)
its giving this error steve.
And have you tried adding the missing Attribute?
i dont see the blue thing on the ground
Whats the difference between rigidbody.addForce and .velocity?
Cause I've tried both and .velocity seems slower than ```cs
rbd.AddForce(new Vector3(horizontal, 0, vertical) * (Speed * 10) * Time.deltaTime, ForceMode.Impulse);
like how?
Seriously, you've never added an attribute to a class?
i tried but no use.
isn't this supposed to rename the Element 0 in a list to the stat type? it's not working
probably implementing a method is not supporting in interface.
I think I might have mentioned that some time ago
right.
pretty sure Unity C# level does not support it
the ground isnt baking
I'm not sure if I can explain this correctly but do you need Null in your coding when you already have Mathf.Infinity ?
Don't know what you did wrong but this does, indeed, work
https://hatebin.com/nhyagkkwyl
These are 2 completely different types and values.
What does it return?
See the warning at the bottom of the inspector? Read it. Then follow the link and read it.
1 issue I found and that was that it wasn't the first variable, but still I need to set the name myself instead of using the =>. I swear I remember using that before. maybe because it's in a scriptable object?
It should return a string representing the name of the element. If it doesn't, then you're doing something wrong.
https://learn.microsoft.com/en-us/dotnet/api/system.enum.tostring?view=net-8.0&utm_source=perplexity
In Unity, List<T> doesn't call the class' default constructor. It uses reflection (supposedly) to assign every variable to its Type's default

This applies to non-static and non-readonly variables
I don't get it
I don't see any lists in their code. I think they mistakenly called enum a list.
no I made a list of Stat classes
rename the Element 0 in a list
though I swear I've done it like that before and it worked, or I'm hallucinating
When creating a class, you call its constructor. Otherwise, doing this inside of the local method causes a warning on unassigned variable usage.
In Unity, creating a List via the inspector doesn't access any constructor of your class. Instead, the class will be created with all variables set to their Type's defaults, which is null for reference types as string and any other class and Vector2.zero for Vector2, 0f for float etc. That's why, if your class or struct is meant to be used inside of the serialized in the Unity's inspector List, assigning the variables doesn't change anything, unless they are static, readonly or const.
The same applies to arrays. Not sure whether they serialize some other Enumerables
copy the playermovement class, delete the file, create a new file, paste / or delete the .meta file
so it just doesn't work
I guess I'll settle for pressing a button then
To add to my previous response, only the 0th list element is created as default. The others are the copies of the previous one
What's also an option, you could make your script run in the editor and check for the list count changed in Update
I mostly just want it to update when I change variables
When should it be updated?
for instance if I change the stat requirement's stat to Dexterity
You can achieve this by creating a custom PropertyDrawer for your ScriptableObject
never worked with those
This will be tricky, since you'll have to completely override the List's serialization by getting its IEnumerator and serializing each variable separately, checking whether the suitable one is changed by wrapping it with EditorGUI.BeginChangeCheck
I think I'll leave it for another time then xD this is just a small project to prep for my exam
I'll add it to the list of things I wanna learn tho 
yes it worked. i didnt checked i was using abstract class.๐ .and even with abstract class also it worked but i forgot to check that i removed the implementation of abstract class.๐ .
Got it. Reply to this message if you happen to start it, since I already have the similar logic implemented in my extension class

I'm having an issue with the AgentLinkMover.cs where the agent can only cross the navmesh link once. If it tries to cross the link again, it freezes
I'm using the Curve option
I'm not sure why since I literally pasted the code straight from the NavMeshComponents repository
But the issue is with this script cause they can cross the link multiple times without it
Have you tried using breakpoints and the debugger to see what is going on.
From what I tried with debugging, it doesn't enter the if statements the second time round for some reason
Are your offmeshlinks bidirectional?
Yeah
I'm not trying to make the agent cross back and forth, it's a race kinda like Koopa The Quick
so if the player loses, they can retry the race
but retrying the race gets the agent stuck not crossing the link
Is it because your code always goes from the current position towards data.endPos?
Should it go towards data.startPos when crossing back?
I don't think so since it's going from the start point to the end point every time.
I see
After it runs the course, the agent is deactivated and set back to the beginning of the course
Then it's activated again but it can no longer cross links
you know that code will only run again if you reload the scene
really?
yes, it's in Start, Start only runs once
so I've gotta move it elsewhere then,
probably into Update
I've just not seen this issue before
not into Update. Into a Coroutine you start from Start
well
it's an infinite loop
it should keep running indefinitely
but yeah you should be Logging to see if it ever sees isOnOffMeshLink again
tf Visual Studio suggesting me to do ๐
It's very possible that's legit if the User contains a complex hierarchy of objects
that being said, it's AI stuff
random question if you have a reference to a script on a gameobject that is disabled, can you update it's variables?
I'm guessing not
yes
it does?!
the only thing that doesnt run is Update and stuff like that
because its disabled
the rest acts the same

why not
idk, I just imagined if the gameobject was disabled that u wouldn't be able to do stuff inside of it
You imagined wrong I guess
Also the GameObject cannot be disabled
Scripts can be disabled. The GameObject can be deactivated
ah right, mb
you know if you spent more time researching and less guessing and assuming you might learn something
well yea that's why I asked the question
try reading the docs first
Still having the issue after moving it into its own Coroutine,
yeah that wouldn't have made a difference
I think deactivating the GameObject is stopping the Coroutine actually i might need to move it
to like OnEnable
yes if you're deactivating the object it will stop the coroutine
duhh thats obvious in hindsight
alright thats what it is
makes so much sense now
starting the coroutine in OnEnable should finally fix this
don't forget to stop the coroutine in OnDisable
Alright,
I still canโt believe Unity actually shipped this junk code in a real repo ๐คฃ
Well assuming you don't disable the gameobject like I am, it works
Working code does not mean it is not junk
True
The whole concept of doing this in an infinite loop inside a coroutine is just bonkers
Anyone know how i can implement the spring damper code here to be used for anything, like camera shake or gun recoil or a camera fov zoom? https://x.com/wilnyl/status/1201516498445058048
@haanssksum Thank you!
I dont think so.
The code is basically:
Velocity += (targetPos - currentPos) * spring;
Velocity -= drag * velocity;
CurrentPos += Velocity
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ooh, im not really sure how to format it the right way just found this on X about an example with springs, and have no idea how to actually implement that
then just show that code properly
i and probably others dont want to go on X to look up code you want to implement...
ok, this is all that it is i think just copied it as it is and put it in here, https://gdl.space/vaxurowego.makefile
this wouldnt really give you gun recoil or camera fov zoom
I use box collider with animation keys(enable colliders for exact times) for sword attack in 3d game. Unity sword attack collider not working with increased animation speed. What is the best way to do sword attack detection for high speed animations. Any help would be nice.
yea, thats why im asking about how to turn this to be utilized for that, in the post he shows an example of a spring damper and then says in the replies, that this was basically the code used for it
dont use this, just follow a tutorial on youtube.
the main way it works would just be lerp from current position to a default position which you can add to it
if i were to use it just for camera shake which is how it was shown in that example, would i just need to use one c# script for it without adding any others components?
i guess you wouldnt, but im not sure
write a code to decrease animation speed when collided.
They cannot detect a collision in the first place, so that wouldn't work. It would also look weird.
First choice would be a physics query if you can, if it matches the movement of the sword. But you might need to either do a few checks or some overlap sphere and see if the enemy is within a certain angle
Did you also play around with the rigidbody values for collisiondetectionmode. Maybe speculative might already improve things?
Also consider to increase the timestep value if you need faster collision detection
i now that but my enemy object just using navmash agent. not using rb component.
But the collision of your sword is not related to navmesh agent, or is it?
i have 3 animation for sword so i need to 3 different collider right. I read about that method and it makes sence to me
The collider is located on the agent child object.
and this is the enemy
It might help if the collider was enabled
And how do you check the collision again?
I guess its just disabled for this animation clip
Usually you dont need exact hit detection along with the sword, just having a general hit area should be fine using basic physics queries.
when attack animation is started collider will enable
yes
i have 3 different attack animation like combo attacs
Just to be clear, you have to use the physics system to get correct collisions for those colliders. It has nothing to do with navmesh agent doing its own "collsion" checks for the navigation
thats why i avoid that method but i think have to do it that way
And also one of both needs a rigidbody attached to actually get the collision events to be fired
continues detection is expensive i suppose
i am making this game for mobile
You can always switch the mode when you attack for the time of animating. But if you want super fast detection, you need to use that. If you can work around it with your own predictive box or sphere overlap checks, because you dont need like arcade fighter game like collision checks, try to work that way
in my case i have lots of enemys but as u say enemys dont have multiple colliders for head damage or something
yeah, just go from animated colliders and collison checks to distance checks and when animating use like a fixed attack rate that gets triggered as you like and checks if the player or whoever is in front of the enemy.
"The easiest way, start timer after executing hit and then check if target is in range. You donโt need really fast collision detection. You could also use raycast, when executing hit." i saw that on forums. What do you think about that
You could also twist it around and let only the player (if thats the case) check for enemys around him, if yes, they get "enabled" and can attack with that timer or whatever you wanna use to have the attack rate going. Really depends on the style of your game as well as the feeling of it
This ignores 1 thing, your problem was actually detecting the target. The raycast just ensures you arent doing this through a wall
A lot of this also depends what you want a hit to actually be. In some games, your sword goes straight from right to left in 2 frames. In some games (example: souls like games) its much slower
In the fast cases you could just detect the whole area infront of the player
same problem with collider gonna happen to raycast right
No but that raycast was likely a suggestion to make sure the target is visible. I hope at least
Not to actually get the target
Because a raycast will get 1 target in a straight line. You want something probably to get all enemies in front of you
yeah
Maybe you need a multiple step check. First check the distance with a static vector for the player position against enemy. then, if in range, do a raycast to check if visible, if yes, do your box collision check or whatever to actually hit the player. But best would be you writing down yoru mechanics and then what systems could help you achieve those states you got in your mechanics. Find common routes and try to sum it up to reduce calls for physics and what not.
Maybe you can share a little bit more information about what the enemies are doing, can do. Who will they attack, only the player? and so on. Thats important to get a proper solution
i can share quick gameplay in dm
is that okey for u
@eternal needle https://youtu.be/j2OCes42qvg?t=1476
You suggested me to do a method similar to the one here, right?
BUGFIX
https://youtu.be/AgmBIHlD12k
In this video we create a new weapon component. This component is responsible for defining a HitBox for the weapon and detecting entities within that hitbox.
All Assets:
https://drive.google.com/drive/folders/17JbMy70gbXLcPYrIIpwYt7xJmKngu0oB?usp=sharing
Discord Server:
https://discord.gg/uHQrf7K
If yo...
I can't watch rn I'm at work
I've solved the issue regarding this, The torque I added was adding the weird gliding effect so I just removed it for now.
What's the best way to create documentation from code?
I would like a way to add descriptions in the code itself and later generate some docs from it
XML is indeed my favorite as well
very useful
The code GeometryUtility.CalculateFrustumPlanes(cam) gives me an error of Object reference not set to an instance of an object any help would be appriciated
Show the full stack trace of your error
it is saying your camera doesnt exist
but it's likely that cam is null
and is not referenced
UnityEngine.GeometryUtility.CalculateFrustumPlanes (UnityEngine.Camera camera, UnityEngine.Plane[] planes) (at <cb81df0c49c643b1a04d9fc6ccca2433>:0)
UnityEngine.GeometryUtility.CalculateFrustumPlanes (UnityEngine.Camera camera) (at <cb81df0c49c643b1a04d9fc6ccca2433>:0)
CameraDetector.Start () (at Assets/Scripts/Player/CameraDetector.cs:15)
Yeah cam is defiinitely null
make sure you assign the variable before trying to use it
Why does it need to be so hard to multiply two Vector3s ):
There are at least three different ways to multiply them
Because there's multiple ways of solving that. Would it multiply each corresponding component (X * X, Y * Y, Z * Z), or all of them one by one like a matrix multiplication (X* X, X* Y, X * Z, Y * X, ...)?
I don't get why you can't just (Vec3Var * Vec3Var2)- they really couldn't code that in?
Because it doesnt make sense. That's not a thing in the math world
And as they said above, it could mean multiple things
Some may even consider that the cross product in the math world
Which kind of multiplication are you looking for?
They could certainly do it. But it would be ambigious and unclear what kind of multiplication that would be. And if they picked one type of multiplication there would be people up in arms that a different type wasn't chosen.
It makes sense to me- you just multiply each number with its counterpart, like how you have to do it in the actual scripting: (Vec3Var.x * Vec3Var2.x, Vec3Var.y * Vec3Var2.y, Vec3Var.z * Vec3Var2.z)
ok but that's like, the least common way that vectors are multiplied
I use it all the time /:
In mathematics, vector multiplication may refer to one of several operations between two (or more) vectors. It may concern any of the following articles:
Dot product โ also known as the "scalar product", a binary operation that takes two vectors and returns a scalar quantity. The dot product of two vectors can be defined as the product of the m...
Dot product and cross product are insanely common
much more so than the hadamard product
Can always make an Extension method so you don't have to do it manually
You don't have to - just use Vector3.Scale(Vec3Var, Vec3Var2)
(As navarone pointed out above)
HLSL implements the * operator as per-component multiplication. It makes sense to me in that context, but I suppose it's more common in shaders than in scripts.
Look none of us work for Unity, they could certainly have chosen to do it. They didn't. We're just provided post-hoc guesses and reasonings about why
Unrelated to the above conversation- does a C# counterpart to this exist?
(val1 if bool else val2)
myBool ? val1 : val2```
you're clearly a Python person
Yeah lol
Unity Mathematics' float3 implements component-wise multiplication operator like HLSL. Maybe you can use that in place of Vector3, even if only in certain scopes and converting between them when necessary.
well not really, it uses the mul function
so you'd write mul(vec1, vec2)
which is equivalent to Vector3.Scale(vec1, vec2)
Learning Python in computer class surprisingly enough has really helped with learning C#- I didn't know how to properly learn a coding language before then lol
Learning ANY programming language makes learning others 100X easier
hmm - so it does
Well, except for Visual Scripting, which is why the above conversation exists.
nah, even visual scripting
the concepts are the same
just a different presentation
the whole idea of data flowing from one place to another and being manipulated, it's always the same.
(In Visual Scripting, Vec3 * Vec32 = Vector3.scale(Vec3, Vec32))
Plus the way I learned Visual Scripting was by looking through the menus and you can't just do that with other programming languages lol
Anyway enough talk about VS let's change the topic before anyone gets mad
Does this look good?
while (Vector3.Distance(transform.position, IsTransform ? destination.position : destinationv3) > 0.1f)
Ternary expressions often arent fun to read in expressions like that
no, you are evaluating something multiple times which doesn't need to be
depends what you mean by "good"
It looks syntactically correct.
What am I reevaluating too many times? Each comparison is comparing different things
IsTransform ? destination.position : destinationv3 each time the loop happens
the ternary expression
Vector3 destination = IsTransform ? destination.position : destinationv3;
while (Vector3.Distance(transform.position, destination) > 0.1f) {
...
}```
This would be better
and easier to read
This is how you know I've been up for 16 hours lol
How didn't I think of that ๐
wdym, I've been up for 16 hours
I still have a lot to learn, but I am actually learning! Thanks for the guidance, everyone!
(No, my way of learning isn't by asking other people lol I just couldn't find any documentation about these)
It's called a ternary expression, which the docs for exist. Often I have trouble finding the docs for symbols because google just seemingly ignores it
So I know GetComponent<>() is horrible for optimization, but how would I avoid using that is a situation where I would need to get a specific component without an explicit reference?
You can use it whenever you need it, such as getting a component off an object at runtime.
But if you find yourself constantly getting the same component off the same object (such as in a loop/update), then you cache it
several ways, singleton and dependancy injection being two
Can someone help with this script? Not sure whats wrong with it.
So this is fine if I don't do it very frequently? (ignore my non-monospaced font i don't need one cuz I don't use whatever feature requires one)
use the fully qualified name of whatever you're trying to use
Yeah I just explained what you need to do
Replace MinAttribute with UnityEngine.MinAttribute or UnityEngine.Postprocessing.MinAttribute
depending on which one you want.
You can also do using MinAttribute = UnityEngine.MinAttribute; or whichever one you want
wdym 'for some reason' you have a very clear error message
sorry im new to unity so im not very good with c sharp
Or using MinAttribute = UnityEngine.PostProcessing.MinAttribute/using MinAttribute = UnityEngine.MinAttribute at the top
Yeah, this is fine. Personally though, I would put a component script on that object and have it cache the animator, then call a function on it to play a specific animation.
I'm sure you are not new to reading though
does this mean i cant use enemy code again? im so confused
You can't have two variables with the same name in the same scope
int x = 5;
int y = 6;
int x = 4;``` is not allowed
nor is
int x = 5;
List<int> someListOfInts = whatever;
foreach (int x in someListOfInts) {
}```
That's basics of programming btw!
I mean that one Praetor said isn't something advanced in programming. You have to learn fundamentals first.
ok but i said enemy in enemIES not enemy again
Hi, I'm trying to create a 2D game using visual scripting and tilemap, except I have a problem, when I move my character from left to right with the keyboard sometimes it gets stuck in place in one direction as I press my key, can anyone help me?
Is that code enclosed in a method?
what do you mean?
I mean where you have this code?
in Turret Script
This is the C# scripting channel, you should use the #763499475641172029 server for visual scripting questions
ah okay I hadn't seen it sorry
No worries
enemies is not the problem. It's enemy that you declare (create) in the foreach loop. It's yelling at you because, a few lines above that, you also declare a variable named enemy
OH
You cannot have multiple local variables with the same name
all of the min attributes or the one at the top
every time you get that error
okay thanks
alternatively - as mentioned - use this
Yes i got it to work
i am so unimaginably slightly annoyed by this
CS1503 Argument 1: cannot convert from 'bool' to 'System.Func<bool>'
IEnumerator WaitForEnd()
{
float Percentage = Variables.ActiveScene.Get<float>("Percentage");
yield return new WaitUntil(Percentage == 100f);
}
my character wont move because of this
did you make sure that the input button you are attempting to use is actually set up in the input settings?
perhaps if you read the WaitUntil docs you would be less annoyed
it was in a custom package called realistic fps prefab im using
and? the input button is not set up in your project settings therefore it does not work
neither of those are called Left
so i just call it left
I already did- there's nothing there that I can tell is relevant to my issue
of course there is. Waituntil requires a method that returns a bool. you are trying to pass an expression that returns a bool
does it compile?
Yeh
then it is correct
Overly complicated :D because :D isn't allowed for some reason!
Hey! is it possible to use inventory.Contain to see if itemName is equal to "string"?
cs
public List<Inventory> inventory = new();
[System.Serializable]
public class Inventory
{
public string itemName;
public Item itemData;
}
use Exists instead
only if you write a custom comparer for the List
I'd use >= 100f, as floats cannot be represented exactly by computers, there might be cases where it'll never be exactly equal to 100, it'll be more like 100.0000000003
In the Visual Scripting code that sets Percentage, it sets it to 100 as an integer when done, dw.
then you should be using a int not a float
The percentage can contain decimals
Then definitely use >=
but what SPR2 still stands. 100 cannot be represented exactly as a float
So this?
Even if you "round" it, most floats won't be accurately stored
100, not 99, but that's the gist of it
๐ฌ
That WaitUntil will never finish
99.8
because your local variable is not going to keep updating.
Good catch ๐
you would do cs yield return new WaitUntil(() => Variables.ActiveScene.Get<float>("Percentage") >= 99f);
And if you don't plan on putting any code after the yield, or that this coroutine isn't awaited from another coroutine, it's esentially useless. It won't block the function that executed StartCoroutine() from running. In fact it will proceed with the rest of the code immediately after hitting the first yield
Oh. So how would I properly do that?
You'll need to put whatever you're waiting to do in the coroutine, after the wait
The coroutine only delays itself
What if I made the source method a coroutine?
...
Ending()
void Ending()
{
// code
}
to
...
StartCoroutine(Ending())
IEnumerator Ending()
{
yield return null;
// code
}
You'd need to still start the coroutine
But as long as you call it with StartCoroutine it doesn't matter what you name it
it'll run until it hits a yield, wait for whatever condition you've specified, then continue from there
...
how do i direct it directly to the main unity thread without chaining yields- all i want to do is just run one thing that takes some time, and then run another thing without overlap
Coroutines aren't multi threaded
Do you have time to give me a example?
is the example in the documentation that i linked not sufficient?
Is there any way to do this?
Thing 1- Takes time to execute, pauses this thread without freezing Unity
Other stuff
Well again they're not threads
but yeah just write it in your coroutine
IEnumerator Example() {
// some stuff that takes time
// some other stuff that happens after the first stuff
}```
Wait, so I can actually nest coroutines and waiting will work as expected?
depends what you mean by nesting coroutines
if you want to start a coroutine from another coroutine you either
yield return OtherCoroutine(); // waits for it to finish
or yield return StartCoroutine(OtherCoroutine()); // waits for it to finish
or StartCoroutine(OtherCoroutine()); // doesn't wait for it to finish
Like this:
Coroutine1
StartCoroutine(Coroutine2) // Waits for Coroutine2 to stop waiting
//Other Code
Coroutine2
// Code that waits
Ah
C# is daunting... I'm a little tempted to go back to Visual Scripting but I won't lol
Coroutines are a Unity thing only
They're not part of regular C#, though the feature they are built upon IS part of C#
Unity oriented C# is daunting... I'm a little tempted to go back to Visual Scripting but I won't lol*
the whole IEnumerator and yield thing - those are for iterator methods which is C#.
Oops- forgot that I reverted my change of making Ending() a coroutine lol
im trying to make a raycast go in the direction of movement so like any sane person I used the RB's velocity + the forward direction of my playerleghitpos object. but instead of it not hitting something, its hitting something when it should not be, if i move far away from any stairs it seems to not hit anything. so i havent a clue what is happening ๐
Debug.DrawRay(playerlegpos.position, rbvelocityXY.normalized * staircheck);
rbvelocityXY = new Vector3(rb.velocity.x, 0, rb.velocity.z);
if(Physics.Raycast(playerlegpos.position, rbvelocityXY.normalized * staircheck, out hit3, stairmask))
{
Debug.Log("hitting stairs!");
}
If you want to raycast in the direction of movement that would just be the velocity
i dont want it to measure Y movement
if(Physics.Raycast(playerlegpos.position, rbvelocityXY.normalized * staircheck, out hit3, stairmask)```
This looks incorrect. It looks like you put the mask in the `maxDistance` parameter
rbvelocityXY.normalized * staircheck < stairCheck will be ignored here
it doesn't care about the length of this vector
only the direction
You want probably:
if(Physics.Raycast(playerlegpos.position, rbvelocityXY.normalized, out hit3, staircheck, stairmask))```
that will do it, thanks for correcting my mistake, went right over my head ๐
It's unfortunate that DrawRay and Raycast use different conventions
it leads to much confustion
yeah i havent a clue why they are like that
i wrote my own Draw.Ray() that works by passing in the ray itself
eh, it's not really even all that necessary in recent unity versions to draw the ray manually (unless you're using 2d) because of the physics debugging window that will draw your queries
this is a code channel
I've copied the contents of the file, and deleted it. Searched for anything else under the name "PlayerMovement" nothing. Then I recreated the file, pasted the contents and still the same outcome. When I try adding it, it gives me the same error. And when I look it up when I click "Add Component" it doesn't show up.
I'm starting to think ALL of my projects are just cursed
try create a new script inthe add component window but with a different name and paste the class that renamed with the current file name
Welp that worked. That's REALLY stupid
Thanks
why is it saying im not using Update or Gizmos while im clearly using them and have codes in them
you have those methods nested inside of another method. therefore they are not actually in use
so the {} is placed wrong?
show the whole code
those warnings are in the vs not in unity
yes your brackets are all messed up
if you use proper indentation/formatting it will be much easier to see
and using explicit access modifiers on your methods will really make it obvious when one is nested inside of another
fixed thanks guys
why did I read raycast as racist ๐
You should have a conversation with yourself and a timeout . . .
can someone help me out with this i tried debugging but it didnt work
partToRotate is what?
is the head that moves the turret
mostly supports the turret to move its head
yes but what is it, Transform?
yeah
so your trying to give the lerp a Transform
but it takes 2 quaternions
and a float
so i should only have 2?
i typed like 4 quaterions in the code tho
theres only 1 in the lerp
i did it like this
huh
you said make 2 so i did
I already hate quaternions
this has nothing to do with quaternions
nothing here your doing is complicated
its just your lack of copy pasting / basic C# knowledge
even in the manual its too complex
or its just me yeah
now its giving me Lerp error
i checked everything it seemed like everything was in order with the video
Nope, Lerp needs two Quaternion and one float, you're only passing one Quaternion and one float
You probably need to involve your lookRotation variable (created on the line above) in the calculation.
you literally deleted the other quaternion for no reason
What do I made wrong?
Trying to access a key that does t exist. The error says it all.
But I have this key
what is this
I don't know. You should know that.
I misunderstood what you wrote, why I'm not accessing these key('s)?
Because I don't see you accessing them anywhere.
Do you even understand what line throws the error?
yes
What line is it?
Debug.Log(Values.IntsContainer[i.name]);
or simply, Values.IntsContainer[i.name]
How to do that
Great, so what are you doing on these lines?
try to find the value through the key
key is = my text name
Yep. So the keys that you use here must be missing in the dictionary
okay...
Try debugging the keys before using them.
I'll try
Nothing debug
Share the updated code
Uh... I don't hung up the script to the some object on the scene...
Anyone know how i can make a spring feature like the one shown in this video at 1:30 to affect the scale rotation or position of an object and also be able to bump an object. I tried following along with it but it just seems way to complex and i dont really seem to understand how to implement it. https://www.youtube.com/watch?v=6mR7NSsi91Y
Something a lot of young indies skip over is the "juice factor" of their game. Simple, bland transitions and movement leaves the game feeling boring. This week you can not only learn about Springs and how to use them, but also get a framework to use them in your game today!
Springs allow us to move, rotate, and scale objects in a, well, spring...
look up how to tween objects, because that's pretty much all it is, is tweening using different easing functions
is lean tween the good idea for tweening?
there are several good options, lean tween is one of them. I haven't personally used it though. I've used DOTween and PrimeTween and thought they were both pretty good
is there another way to do it without tweening though? like just using damping and frequency value for a spring like movement?
like how landfall uses springs for stuff shown here https://x.com/wilnyl/status/1201511388872617985
you know that tweet that is a few replies in that provides a few lines of code? that's pretty much the easing function they are using
yea i saw that, i dont rlly know how to utilize that and what else to put into the script to make it work though
in this video, he shows you what he is doing and how to implement springs into unity using a public github spring class
hey anyone know a good tutorial that shows you how to make a 3d object move cant find one or it dose not work and I'm trying learn how to do it not ctrl c it
i mean, the code itself is incredibly self explanatory. Velocity is obviously the direction and speed of the movement. targetPos is clearly the target position, and CurrentPos is the current position. from there you have two other variables, spring and drag which are obviously those other values you want to just plug in.
(hint: it's literally just tweening)
this is very vague because do you want an FPS controller?Third Person Controller? Car controller? etc
usually using a CharacterController or Rigidbody
FPS controller sorry
that what I was trying to do but it did not work for the CharacterController
you followed the tutorial wrong then or did something wrong with your setup
then show what you tried and explain what isn't working the way you expect it to
So I try to see if it works first before I try to learn it I copy and paste it and follow the guy how he show it and it didnโt work donโt know why mb because itโs old so I try a more newer tutorial so I did the same thing copy and paste, and it still doesnโt work
i get what they each of them mean but like, i dont know how to put it into a script. Like do i put that code in start or update or something else and do i need to make a variable for each one like velocity, targetpos, currentpos, spring and drag? And is that like all the code i need besides just make variables and assigning a value to them?
well you obviously need to call it over time because calling it just once will only move it one frame's worth of that movement. so clearly it should go in Update or a coroutine, or something that is called repeatedly. And you obviously need variables for the different variables in the function.
You should probably go through some beginner courses like the pathways on the unity !learn site if you don't know how to do any of that
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
alr so i just need to put it in like private void update? and then just make a public float variable for spring and drag and a vector3 for targetpos and currentpos? not sure what to do for the velocity variable though
the velocity is just the RB's velocity
all of the data that will be assigned to Velocity is right there in the existing code
boxfriend is basically telling you to learn #๐ปโcode-beginner message
you must learn the basics before you dive into things like this
so i just need to make variables for the other things to get it working?
yea idk, i try learning the basics but idkr how to use that to then understand slightly more complicated specific stuff with that info
then you did something wrong most likely, but we dont know without seeing anything of what your doing
if you dont know how to assign variables, make vectors, floats, etc you must learn how to using the link boxfriend provided
or follow a tutorial on youtube
i think i got the other variables set correctly, just not sure how to do the currentPos/CurrentPos and the velocity/Velocity ones
well as stated before, the velocity(s) are most likely a RB velocity, the Currentpos(s) are probably vector3's
there is no rigidbody involved here
then the Velocity(s) are a vector3 or a transform's position
i just looked at the tweet, my bad
do you know what i need to do for the Velocity Vector3's and the CurrentPos vector3's?
cause they both need to be getting constantly set right?
if you would bother going through the pathways on the unity learn site, you might have some idea what you may need for the CurrentPos variable
Whenever I try to use Random.Range(); with even explicitly floating point numbers, it still complains about them not being integers despite supporting floats?
are you still trying to assign the result to an int variable?
Oh
ok i think i maybe figured out how to set them correctly, not sure though
well you've missed the crucial step of actually using the currentPos variable
where do i need to use it though? i thought it was being used on the bottom chunk of code part, im confused lol
you only use it in the one calculation. you never assign to the position with it
also all the Velocity and currentPos can be made the same capitalization right? cause originally the it has currentPos and CurrentPos and Velocity and velocity
uh where do i assign it so it works with the spring code?
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
oh wait is this it, do i just need to flip currentPos = transform.position; around so it sets the position of the object to the currentPos? I dont really understand still
i believe he asked you to learn multiple times now
ik, im just trying to figure out this one part though cause i already understand a little bit about variables. And i think i got it correct now, just not sure
if you think you have it, try it and see
nope it doesn't work, rip
you have to update your position after you set the variable
oh so it was right like this before? i dont understand
ok
no
thats not what i mean
this line 23 needs to be after line 27
ohh like this?
yeah
and i assume you need to lerp Velocity or currentPos back to 0 or whatever the default position is
(but you can figure this out later if you need)
when i changed that line to be at the bottom of void update its giving me this error now
lol
might need to clamp the numbers or something
hold on ๐ค
why is this on a Cube? when its camera shake
im just testing it on a cube atm so i can visualize it a lil better
also wanna be able to change this code so i can move it to a point instead of just shaking them with a spring like motion
by my calculation if this runs once the y position will be -100
do Mathf.Clamp(Velocity.x, 0, 10f); above currentPos += Velocity;
see if that helps anything
rip im still getting the error
show where you put this and whats the error
its saying it has to do with the line 22 (line 23 now), its at the bottom
do the same but currentPos.x instead of Velocity.x and put it underneath instead of above
that clamp won't do anything btw
you're ignoring the result
anyway you're getting a NaN in there somewhere - and it's not coming from this code.
you're not saving the value returned from Mathf.Clamp . . .
same error still on line 23
you are trying to move the cube at an infinite speed which is not possible
they suggested to clamp the value
but you are ignoring the result of the clamp
to infinity, and BEYOND! ๐
Hi, everyone, Nice to meet you.
yea idrk, i just put the clamp where he told me and that it might fix it
yeah i forgot you need to store the value so just currentPos.x = Mathf...
you need to understand how to use the method . . .
look at the mathf.clamp documentation
sorry to interrupt you.
ok, i tried that but im still getting the error for some reason
ah im stupid, its .y
because your using the Y position not X
np lol
this is a help channel, if your asking questions / helping people then its not interrupting
!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 #854851968446365696
speak up
ok yea that got rid of the error but idek what's going on ): its just teleporting to 0, 0, 0 instantly and not doing anything
probably because from my calculations it should be -100 which means its under 0, but you clamp it to 0
try making the clamp -50, 50
instead of 0, 10
uh now it just teleports somewhere where i can't see it anymore
yeah i mean because its a high number, the most you would wanna move it is like under 1 probably
but if the value is always smaller then you will never see a "shake"
this code is pointless
yea idk lol, i found a longer video (https://www.youtube.com/watch?v=eaymdtBHpxM) of the code block that i had linked earlier being used, which is basically how i want it to be able to be used, to move objects to spot or be able to change scale or rotate, and also for a camera shake (so its like pretty modular and can be used for a bunch of different uses in my game in the future like recoil or something on a gun) . I thought the camera shake would be easier so that's why i was starting with that. This is where (https://x.com/wilnyl/status/1201516498445058048) he said the what the code for this example basically just is, and someone in the replies said they were able to use that for a camera shaker.
@haanssksum Thank you!
I dont think so.
The code is basically:
Velocity += (targetPos - currentPos) * spring;
Velocity -= drag * velocity;
CurrentPos += Velocity
also to clarify, the person in this video tells you how to set up actual code instead of a reply on twitter
you probably need https://docs.unity3d.com/Manual/class-SpringJoint.html or if theres another component
since its "physics"
and you have literally zero physics lmao
yea im not sure if its actually physics based or he's just saying that cause it looks like it, but he said in the replies on another tweet about working on the slide is that the motion is all spring damper based, not exactly sure what that means.
yeah its definitely using that Component i think
yea i just didnt really understand it much, and rather decided to go with the other code since the person that made it is from landfall games and the style that i'm trying to go for is very simliar to theirs with how it uses springs/physics and stuff for a lot of things.
here is the code actually working after making the necessary changes to work. the issue isn't that they are missing a component or anything, they just don't understand what they are doing so they don't know what changes to make to get it to work
that is also using 10 and 2 which were the spring and drag values they attempted to use
honestly, this is similar, if not, the same as Lerp using an easing function for t . . .
yes, it's literally just an easing function that replicates a spring
so just use an easing function, or an animation curve where you replicate the (spring) curve you want . . .
yea thats exactly what im trying to do maybe just a little less strong, didnt know how the values were going to make it turn out till it actually worked so i was gonna tweak them after.
i still have no idea what changes to make to get it to work though, and cant seem to figure it out at all no matter what i try and look at lol
try going through the pathways on the unity !learn site to learn how to use the engine and you might have some clue as to what needs to change
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
I have a misunderstanding regarding to setting a gameobject position. If i call this line the first time, the position goes the 1,1,1 position.
But if i call the same line again, it translates the object to 2,2,2 but i just want to set this gameObject exact position to 1,1,1 again. How can i achieve this?
gameObject.transform.position = new Vector3(1,1,1);
no, that line will not set the position to 2,2,2
Hi! I have a problem with movement
in 3d
it works fine, but every time i stuble upon an obstacle that makes my player go up a bit, he keeps moving up and flying
private void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
private void Update()
{
// ground check
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
MyInput();
SpeedControl();
// handle drag
if (grounded)
{
rb.drag = groundDrag;
Debug.Log("Grounded");
}
else
rb.drag = 0;
}
private void FixedUpdate()
{
MovePlayer();
}
private void MyInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
}
private void MovePlayer()
{
// Calculate movement direction
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
Vector3 targetVelocity = moveDirection.normalized * moveSpeed;
if (grounded)
{
rb.velocity = new Vector3(targetVelocity.x, rb.velocity.y, targetVelocity.z);
}
else
{
rb.velocity = new Vector3(targetVelocity.x * airMultiplier, rb.velocity.y, targetVelocity.z * airMultiplier);
}
}
private void SpeedControl()
{
Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
// limit velocity if needed
if(flatVel.magnitude > moveSpeed)
{
Vector3 limitedVel = flatVel.normalized * moveSpeed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
}
}``` That's most of he code, movement isnt stored anywhere else
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
when the white object (player) goes through this black doorstep, it begins flying up
Any ideas?
is it possible to instantiate a particle system and it change it emission amount based on the speed of the charcter?
yeah
Can you show me ?
just instantiate it, store it in a variable, and change its emission amount
Alright, I will try to do it
screenshot your rigidbody
that looks fine. You need to debug your code. especially this line
rb.velocity = new Vector3(targetVelocity.x * airMultiplier, rb.velocity.y, targetVelocity.z * airMultiplier);
turns out this line is always running
So it never counts player as grounded
Sorry this was a stripped down example, it is actually working. My problem is that i use this line of code:
var leftViewportMiddle = Camera.main.ViewportToWorldPoint(new Vector3(0, 0.5f, 0));
This gets the right position at startup, but when i call later in runtine it gets totally wrong position. The position of the camera was remained the same.
I use the camera with Cinamachine if that could be any helpful information. What could cause the problem?
i see rb.velocity.y is causing the problem. rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
hey, I do not know if this is the correct channel to use for this problem. But I just started using unity but it seems I already got errors and I don't know how to fix them. I have been trying to fix them myself without success, I am using 2022.3.45f1 editor. the errors are : Library\PackageCache\com.unity.render-pipelines.core@14.0.11\Runtime\Lighting\ProbeVolume\ProbeReferenceVolume.cs(651,13): error CS0103: The name 'AdditionalGIBakeRequestsManager' does not exist in the current context and Library\PackageCache\com.unity.render-pipelines.core@14.0.11\Runtime\Lighting\ProbeVolume\ProbeReferenceVolume.cs(689,13): error CS0103: The name 'AdditionalGIBakeRequestsManager' does not exist in the current context
This usually implies that your editor version and a package version are not compatible. Did you upgrade a project that was using an older unity version or something?
no I did not. After I installed the editor I created the project
Then it could be an issue with your installation. Or did you use some non default template perhaps?
hm there was a problem with the installation. However the problem was solved when i reopened my computer
What problem?
it complained about storage space (22gb left), but it successfully downloaded when i reopened my computer
There's a chance that it didn't install correctly
Yeah that could be the case, then should I try to install another editor or remove this editor and reinstall it?
Yeah, try reinstalling.
The same version is fine. Just make sure it installs without issues.
Thanks, it wonโt ruin what I have already done in my project?
What have you don't in your project..? Considering you had compilation errors.๐ค
But no, that should ruin it. Though, the error might persist until you reset the project cache.
Yeah, I could code and all that but I could not play the scene.
Ah, did not do much in it. Will be worth it if I can play the scene in the end
hey can someone help with some code its not working
!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 #854851968446365696
are there any good fov tutorials for enemy ai im making a top down 2d game using navmeshplus for pathfinding
Hi! I dont have a quesiton about a particular piece of code, Im more looking for a tool I could use. My armor data is structured like this https://gdl.space/ozodihobop.cs
I would prefer to not do any changes to it and Im looking for a way to nicely look up a specific ItemExtras based on the name (for now Im literally going by indexes like
armorExtras.categories[x].itemExtras[y].animClip'
for example, its fine, but it gets very long in some cases
Maybe just implement getter methods?
clip = item.GetAnimClip(category, index);
extra = item.GetExtras(category, index);
thats solid, thx
how does OnPointerEnter behaves ? i have one that doesn't work even when it's using the same UI prefab with one that works. i'd rather not writing my own raycast if possible but i have no idea what their condition to be detected and executed.
i was hoping that it is "the first to be hit/ closer to camera" but apparently it's not that simple.
I hope I'm in the right channel here but I have a question
I'm very new to this unity stuff but I've been looking into how to decompile a certain game made in Unity, a little game called Bo: Path Of The Teal Lotus
The reason I wanted to decompile it is cause I wanted to start making mods for it, just a fun little personal project
So the thing is, I managed to decompile the game, and the textures I want to alter for the mod I want to make were found in level0.file, but how do you recompile a file like that into a new level0.file except with the altered textures?
You need an event system in the scene and the appropriate raycaster in the scene
you are in the wrong server. We do not allow discussions about decompiling or modding here
Oh, okay, my bad
Off I go then
I have been trying to make make camera movement, and followed some code online, it only works when turning on the x axis, but not for the y axis, is there something I should be checking?
i have it worked but it's inconsistent, as i mentioned they use same UI prefab but one doesnt work.
im making game and suddenly i cant do any like unity shortcuts
like gameobject, transform, and the for loop is weird and different
noit sure what happend
Use the event system to debug the issue. Mainly to see if something else overlaps the object.
it is, thats my problem as my game grows. how do i use event system to detect which UI my pointer is on ?
If it's iincosistent it's probably just that theres some other object in front of it
IPointerEnterHandler is correct
and all my gameobjects arent coloured anymore
they were green before
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
Select it at runtime and it would show info on pointer states.
thanks
doesnt work, so this is https://docs.unity3d.com/2018.1/Documentation/ScriptReference/UI.Selectable.html the one I'm working with (right ?). how do i get the information in reverse, what gameobject(s?) is my pointer is currently at.
Doesn't work? Can you take a screenshot of the event system object at runtime?
this ?
Yes, there should be a preview window at the bottom.
Ah, you're using the new input system. It might not be showing then.๐
Plan b. Pause your game when the issue is easy to reproduce, switch to scene view, focus on the canvas and start clicking in the area where you'd click in the game and see what objects get selected. If among them any undesired objects, uncheck their raycast target, untill only the desired object is being selected.
all my stuffs were anchored to the whole screen so it will choose one of them each click, ill just brute force through everything untill i decide it's not worth it and do it manually.
or start learning this https://docs.unity3d.com/Manual/UIElements.html , this is the fancy new(ish) thing right ?
Should I start from the beginning of the junior programmer part ?
im getting floating point errors where its adding 0.009 randomly instead of the required number how do i fix this
its adding 0.009 randomly instead of the required number
What is "it"?
Sharing your code and the values involved etc would go a long way to us helping you. As well as explaining what you're trying to do.
you don't, that is the nature of floating point numbers
massCount.text = dustCount.ToString() + " Solar Masses";```
0.001f is not a number that can be represented accurately in binary floating point representation
no
it cannot be represented in binary at all
It's like 1/3 in base 10
it becomes 0.333333.....
similarly 1/1000 and 1/10 cannot be represented in binary
https://www.h-schmidt.net/FloatConverter/IEEE754.html < try plugging it in here
so what do i do
What are you trying to do
What do you need numbers that precise for
If you want to do something like this you can make an int or long variable that represents 1/1000s .
There are other ways to represent numbers, depending on your specific use case. If you're doing it for the purposes of precise math, for example
e.g.
long OneThousandthsOfASolarMass;```
Then you just do formatting tricks when you print it
And when you do math, you multiply it by 1000 and use double to do the math itself
oh so if i keep it as an int but then do math as a double then display that it will work
if the math is just adding one 1/1000th, you don't do the math as a double, no
you just add 1
because 1 means a 1/1000th in this scheme
so then how do i display that
Think of it like having a variable for pennies when talking about money in dollars
long OneThousandthsOfASolarMass = 25; // aka 0.0025
Debug.Log($"0.{OneThousandthsOfASolarMass:D4}");```
for example
Here is is in action:
https://dotnetfiddle.net/qVNYd8
Test your C# code online with .NET Fiddle code editor.
When you want to do other math with it, you would do like:
double asDouble = OneThousandthsOfASolarMass / 1000.0;
double totalMass = asDouble * numberOfStars;
long backToIntRepresentation = System.Math.Floor(totalMass * 1000.0);```
massCount.text = ((double)dustCount / 1000).ToString() + " Solar Masses";``` this seems to work for me so im going with this
thanks for help guys
Can anyone help me bit please, I didn't found script for speed and jump.
These my C# Code
look at the input line above the error and spot the difference
You have some basic syntax errors. Double check your code vs examples and make sure you're doing it properly. As you can see from the red underline - you didn't write it properly.
Hmm, so if (Input.GetButtonDown"Jump"))
Were error or something? Im beginner anyway tho
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
!vscode
look at the difference between these two
It's probably just my experience talking but doesn't that look very "wrong" to you? There's no symmetry of the parentheses
What does that green mean?
It means you made a change and saved it
yellow means unsaved changes
Ok uhh, how to Attached that to my object indonesia
(As I start it's still floating)
Probably this
But I already put that on C#
There is no Rigidbody2D attached to the Indonesia game object, but a script is trying to access it
Ah I finally understand, so how do I attached it?
The same way you've attached any component to any object.
You click add component
and then pick it
Aight, I finally found it, thanks.
It may drop but that just because I haven't coded the ground yet, but still thanks.
hey i want to check if the mouse is hovering over any ui object before i call a raycast to select an object (or in general preventing the raycast to go through ui lol)
The best option is to use the UI event system for all the interactions - including your in-game object interaction