#💻┃code-beginner
1 messages · Page 100 of 1
Really?
no theres lots of extra features in visual studio that arent in vscode
and visual studio is build for just .NET and c++ developement wheras vscode is for a lot of languages
You generally download packages, made by 3rd parties sometimes. Before using VSC.
I'm also fairly certain that the C# package (by Microsoft) is discontinued for VSC. But unity has its own package for unity development specifically but VS is still better supported anyways I think.
Yeah visual studio's auto-complete functions are amazing
You also have suggestions.
I like rider better tbh
rider is like $1000000 per month
289 usd per year for the full ide
149 for the min
Real.
The only thing Rider has and VS don't is namespace refactoring in masses.
You do have sync namespaces but come on, it will turn your namespaces into MyGame.Assets.Scripts.. I don't like it.
Hello guys, I have a question:
I am trying to create a 2D Plattformer and I want to have a isGrounded Variable in my PlayerMovement Script. The Script has to know what's Ground and what's not, so I watched a tutorial in which Layers were used to define what is ground and what not. My Question: What's the difference between Layers and Tags? And when to use which one?
The main difference between using Layers or Tags in your context is that you can use Layers in RayCasting (i.e. LayerMasks) to optimise the cast
So in my case tags are the better choice?
no, Layers are the better choice
But my case has nothing to do with RayCasting, or did I understand something wrong?
it's not just RayCasting, that was just an example, it's also useful for optimizing Collisions and Triggers
So when to use tags?
I never use tags
Why is my A* Pathfinding agent returning a desired velocity of 0?
While it is still moving towards a target?
I've checked that I'm including the library, "using pathfinding;", the prefab has a component called AIPath
The AI destination setter gets set
why are you getting and setting values on a prefab?
It's small butters
That wonder around the garden area
I'm using a state machine to set them to wander around
By setting a random target position
that wasn't their point. the point was you are checking those values on the prefab not the instance(s) in the scene
of course the prefab which is not in the scene will have a desiredVelocity of 0 because it is, notably, not in the scene to even get a path
oh
this does make sense actually
yes, oh!
Hello, I'm trying to use DOTween to tween Rig's weight property. But it gives an error
public void SetEnabled(bool status){
rigObject.weight = 1f;
if (status) {
DOTween.Kill(uid);
DOTween.To(rigObject.weight, x => rigObject.weight = x, 1f); // << The error is in this line, in the variable X in second argument.
}
}
Error message is : Cannot implicitly convert type 'string' to 'float'
Cannot implicitly convert type 'double' to 'float'. An explicit conversion exists (are you missing a cast?)
I don't know where the string is coming from.
I think the string is a false positive. Try (float)x
isn't the first parameter of DOTween.To supposed to be a delegate? 🤔
why are you storing the uid btw
you can just do Tween tween
then tween.Kill();
and tween = DOTween.To(...)
and you might want to use DOVirtual.Float
if you want to modify float during X seconds
(startValue, endValue, duration, delegate)
is it like this?
DOVirtual.Float(rigObject.weight,1f,0.2f,() => rigObject.weight = ???)
do I need extra variable to replace nvm ????tween = DOVirtual.Float(rigObject.weight,1f,TWEEN_DURATION, x => rigObject.weight = x);
I don't think you can parse it into float implicitly.
can someone explain why my virtual came change position after i set follow to object amir(player) but when i see on udemy when virtual camera set follow to player(doggy) thats position virtual camera stay ?
"btw sry if my typing english it doesnt good anyway bro🙏 "
jesus christ, finish your thought before pressing enter
your camera is likely not where you think it is
ssshh i cant recrod it on udemy just blank @,@
Can't see anything from the udemy video. Probably protection from piracy.
thats it video from udemy , but sry if my video was blur , coz my camera phone was broken😞
@teal viper thats video from udemy
Do particles collider force work right of the box or do i have to grab the collider force in a script and write it's behaviour?
Solved: Yes it does just work, had to just adjust some settings
Set a raw image's anchor to scale with screen size but the white triangle didn't cover the entire screen?
so tell them that, not me
you have 2 cameras
Hi all i got a question.
In my game right now i have a panel with a scrollbar that has hundreds of different rewards in it.
Those rewards become active when the player levels up.
So say they reach level 10. Then the 10th reward will be available to claim.
The only problem i have is if the player reaches say level 50, they open the panel scroll to the 50th reward claim it and close the panel.
Then when they level up to level 51. They have to scroll again all the way from the 1st reward through to the 51st.
Is there any way that i can save the scrollbar or something so when the player levels up to say level 51 then when they open the panel it will automatically show the 51st reward and they dont need to scroll from the 1st all the way through to the 51st.
Hi all i got a question.
I am making a main menu, however I would like a background image in my main menu. I want to get the background image of my gameplay. How can I get it?
if you want just an image you can take a screenshot and use that. For a video-type background you'd need to generate a mock level or you could simply have your main menu in the gameplay scene.
Hey everybody 👋 I'm making an old school ddrpg game in unity in the style of eye of the beholder. I'm getting stuck on character movement/rotation. I'm having trouble rotating my character and setting where they are looking as their new look position so that i can move forward in that direction. In this case if I want to move forward (by pressing the W key) they move in the original forward vector and not the new rotation forward vector. Any help is greatly appreciated!
New to Unity. Does anyone know what Carl(the guy is the unity tutorials) uses as extentions in his visual studio?
It would help me a lot having to not remember everything word by word
If you mean suggestions, then setup your !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
• Other/None
i have an issue with unity animation it was working fine before i created a andoride build but not its not work any reasons
they are playing in animator but its not show up
If you have an if-case like if(a || b, which condition is tested first?
left to right
That worked but the descriptions dont appear
Can you show a screenshot of your Visual Studio?
Sure
The descriptions do appear while hovering over the written formula
But dont appear in the selection menu
Oh, this is Visual Studio Code...
It is
Should I get both then?
Visual Studio and Visual Studio Code are 2 different programs
What are you looking at from Carl then?
Can you show a screenshot of that?
That looks like Visual Studio, not Visual Studio Code.
yep, definitely not VS Code
Does someone know how I fix this. I just try to put a repository in my unity project but this pops up
I don't think you need us to read that for you
I know what it says but I can't just remove the file
Git LFS should be able too I think
(never tried it)
You should be using the unity gitignore so you're not pushing the Library folder
you shouldn't be committing your Library folder
Why
You need to gitinore yoour unity file otherwise its to large
Ok
Library folder is locally generated when you open the project, there's no reason to commit it.
Ok
It's also massive, as you're seeing
Hello im making a enemy ai system that kills the player when he got hit by the enemy but the problem is that it doenst work do you ❤️ it would help me a lot if you guys know how to fix this problem here are my two codes:
https://pastebin.com/eh5PprRk Enemy
https://pastebin.com/zEH1p8hN Player script
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Probably clarify what part isn't working and what have you debugged
I think the part that isn`t working is collision.collider.CompareTag("Player")) to send you to other scene
i debugged when i touch the enemy but i dont see boom so
well, for one I think you should consider letting the player handle the callbacks for damage when they collide with the enemy
what do you mean by that?
Do you have colliders on both the player and enemy yeah
one of them needs to have a trigger collider is you're using the collision events
I don't think it works if both are trigger colliders though, I'm a little rusty on them
When making a git repos, do you know which option is the library I need to ignore
i added a rigibody to the enemy then its works but the problem than is that he doenst chase the player anymore and just getting stuck or walk to somewere else
A collection of useful .gitignore templates. Contribute to github/gitignore development by creating an account on GitHub.
Ty
Well, if it's logging now then that means it must be working, so what logic you're doing after that is now a different problem ;p
ah, try adding a kinematic to the enemy
than its works but when i touch the enemy i dont die
I'm assuming you're just using trigger events but not the actual physics
only when i disable the is kinematic in the rigibody then the scene would load but the ai is not chasing the player
player has a rigidbody too right?
nope
Honestly, I would just suggest using spherecast at that point then
istead of the rigibody for the enemy or in the script?
Each enemy can spherecast (or circlecast for 2D) around themselves, and you just do the collider checking* through that
what you're trying to do is possible but it's some combination of kinematic rigidbodies and triggers. Oh, actually im confused, maybe you're just using collisional events when you actually want trigger events
Hey guys how you doing ? I have a really simple thing I would like to do,
I have a shadergraph where I have a float property, I would like to change that property accordingly to a timer that I have in a script.
How can I do it ? I'm not familiar with normalize or things like that.
can i send you my unity game so you can fix the problem and tell me wants the problem was
because im trying to fix this problem now for 4 hours straight but i dont have a clue what i need to do
link the float to the timer
Mmh yes, I know I have to do that, but how ?
I haven't seen your scripts 🤷♂️
📃 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.
[SerializeField] private Material paleSkinShader;
[SerializeField] private float timerLenght;
private bool timerCount;
private void Update()
{
if (timerCount)
timer();
else
return;
}
private void timer()
{
float timeLeft = timerLenght;
timeLeft -= Time.deltaTime;
if (timeLeft !< 0)
timerCount = false;
}
(I know it's probably trash, it's just to prove a concept so it's okay)
Hold on let me open unity and check
learning about new() was a gamechanger. Can't believe I've been here for 6 months, and I just learned it a couple weeks ago
wat
should be something like
normalizedValue = (timerValue - minValue) / (maxValue - minValue);
So the first member should be "my timer lenght - time.deltatime" / "my shader property - time.deltatime" ?
not at all
min and max are the values of your timer
if you said 0-5
then min is 0 and max is 5
Ok, I think I know the problem. You're using Collisional events when you want to use Trigger events and I should have realized that. If you're not using rigidbodies for any reason remove them and use OnTriggerEnter instead. Make sure both your enemy and player has their collider set to IsTrigger
timerValue is your current timer time @maiden compass
btw this float timeLeft = timerLenght; should prob not be in update '
since you only want it to set to max in start of timer
You're right
alright, after thats fixed should be able to get it working
float minValue = 0;
float maxValue = 5;
float timerValue = 2.3f;
float normalizedValue = (timerValue - minValue) / (maxValue - minValue);
Debug.Log("Original Timer Value: " + timerValue);
Debug.Log("Normalized Value: " + normalizedValue);```
as An example, gives
Gonna try that ! Thanks !
if (timeLeft !< 0)
fix this too lol
<= would suffice
! means not
so if time left is not smaller than 0 set timer to false
Oh, though it meant strictly inferior
Didn't script in month, I'm rusty
(not that I knew what I was doing before
)
thought you meant you did so much Rust for a second you forgot c# 😏
Would this video tutorial for wall running work if I was using a character controller instead of a rigid body? https://youtu.be/gNt9wBOrQO4?si=CEjm3NCtuuN6ypJG
ADVANCED WALL RUNNING - Unity Tutorial (Remastered)
In this video, I'm finally going to remaster my old wall running tutorial code. This wall running ability feels a lot cleaner!
If this tutorial has helped you in any way, I would really appreciate it if you leave a like in return. And you can also subscribe to this channel if you want to see ...
I'm confusing myself now. Does unity really require rigidbodies for OnTriggerEnter? Why does that even make sense
It should be be independent to that of the collider component
you can use CC with triggers just fine
its a physics object as well 🙂
cc is very similiar to a kinematic rb
its like mix between kinematic and rigidbody or somehing
Yeah, but you can't use the events with the collider component alone
surprisingly OnTriggerEnter can be used with a CC and no rb
only thing that dont work is OnCollision but CC has its own OnControllerColliderHit
Ok, so the docs just using kinematic as an example then
I don't really use the trigger events anymore. Only the collision if needed, otherwise I stick to casting it through updates
No, the docs are just unfortunately wrong. The table at the bottom is at least a bit misleading
hell yeah its wrong, shits moving it with translate
cringe
unity doesn't adhere its own advice
So, uh, should I try using the character controller instead?
@timber tide i fixed the problem now its works ❤️ now i need to fix that if i load the new scene the mouse cursor unlocks do you know how to do that?
probably not since the video relies on rigidbody physics
for like velocity and drag
Ok thanks, I’ll try to find some other tutorial
Allright, I'm lost my man (or girl, I don't know) 🫡
what part?
[SerializeField] private Material paleSkinShader;
[SerializeField] [Range(0f, 5f)] private float TimerLenght;
[SerializeField] private float timerValue;
private bool timerActive;
private void Start()
{
timerValue = 0;
timerActive = true;
}
private void Update()
{
if (timerActive)
Timer();
else
return;
paleSkinShader.SetFloat("_DiffuseBlending", 0f);
}
private void Timer()
{
timerValue += Time.deltaTime;
if (timerValue >= TimerLenght)
timerActive = false;
}
At the "Setfloat" part
I've put 0 so I have no errors, but I can't figure how to put the normalize thing in there. 
well take the example I put and switch up the values 😛
"normalizedValue = (timerValue - minValue) / (maxValue - minValue);" this part ?
Thanks, I'm checking that out. I have a lot of objects because I need a big ocean, and the water assets all seem to work about the same way: Lot's of tiles. Small-ish tiles are needed to the wave effects. I'm absolutely open to suggestions on how to reduce the number of objects though.
[SerializeField] private Material paleSkinShader;
[SerializeField] private float minValue = 0;
[SerializeField] private float maxValue = 5;
private float currentValue;
private bool timerActive;
private void Start()
{
currentValue = maxValue;
timerActive = true;
}
private float NormalizedValue(float timeValue)
{
return (timeValue - minValue) / (maxValue - minValue);
}
private void Update()
{
if (timerActive)
Timer();
else
return;
paleSkinShader.SetFloat("_DiffuseBlending", NormalizedValue(currentValue));
}
private void Timer()
{
currentValue -= Time.deltaTime;
if (currentValue <= minValue)
timerActive = false;
}```
Sorry little busy, but probably describe your problem more and someone might have an idea
Thank you it works like a charm 👌
Really appreciate, have a nice evening 
you too!
Have a bit of a problem where i can use textmeshpro in the editor but whenever i try doing "using TMPro" in my code it isnt recognized by rider. I have the package isntalled under package management so im kinda confused
try Regen Project Files
how would one replace the nested runtimeAnimatorController of an AnimatorOverrideController in unity? Im trying to just set the runtimeAnimatorController within my variable but it doesnt seem to be working..
are you writing code inside an assembly?
Nope, cs script
I that entirely broke my project last time 🙂
It should never do that..
but yeah also checking if you're using Assembly Definitions
Regen Project Files just regens the csproj files
highly doubt it would ever break anything
I do have one assembly definition for my tests
alr well if your script is in that assembly , did you add reference to TMP ?
I don't see how that would be possible
Im not sure tbh, imma just copy my project rq and try regen files
void OnCollisionEnter(Collision collision) {
If(collision.collider.CompareTag("Player")){
Debug.Log("YEY");
}
}
@rich adder this is the basicaly the only stuff in my script
And I said that it is a script problem because I tried adding a collider and rigidbody to the player and nothing
Besides it has character controller
screenshot both colliding objects and their inspector
i fixed it but now i came to new issue now when i shoot a enemy its getting destroyed but when i wait longer in the game it doenst work anymore and the enemy cant be killed anymore its so weird
Hey, i need help. im using unitys new input system, and i want to do that when you move your left stick SIGNIFICANTLY from the position it was last frame, something happens, and if you move it a just a bit from where it was last frame, nothing happens. any help?
I think this but not sure
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/manual/Processors.html
save the input from the last frame and compare it to the input of the current frame.
yes, but how do i check how much it has moved? i want there to be a deciding factor
like if it moved A LOT i want to do something
Vector2.Distance() for example
why not just throw the screenshots on discord
oh
didn't know that was a thing
but what is the max? 1?
A bunch. I dunno exactly
I've seen six in a message before iirc
Edit: sorry, totally misread that.
I thought you meant images lol
up is 1, down is -1, so the max would be 2
oh
ok
so can i do like if (Vector2.Distance(lastStickInput, currentStickInput) < 1)
{
do something
}
After I updated it doesn't let me send screenshot
why isnt my player spawning on the position of the spawnpoint? it is saying its changing but it doesnt. here is the code that runs when the player is created.
private void Awake()
{
DontDestroyOnLoad(gameObject);
if (FindObjectOfType<SpawnPoint>() != null)
{
foreach (SpawnPoint sp in FindObjectsOfType<SpawnPoint>())
{
if (sp.id == id)
{
Transform spawnTransform = sp.transform;
transform.position = spawnTransform.position;
print($"setting transform to spawnpoint {sp.id}, {spawnTransform.position}");
}
}
}
else
{
print("no spawnpoints found! spawning in center");
}
}
you drop the photo in the text chat? it should work
ye, but moving that much in one frame could be quite challenging. You might want to use a timer that updates the lastStickInput every 0.2sec or so instead of every frame.
its meant to spawn on one of the points.
do you use Unitys PlayerController? If so you have to disable it before teleporting the player and then enable it again.
the player is spawned in via the player input manager, but its controlled with rigidbodies
you might need to call MovePosition to teleport it to that position
eg rb.MovePosition(spawnTransform.position);
thats done it, thank you! there is like a frame where it spawns in the center, is it possible to avoid that?
does it still do it if you do rb.position = spawnTransform.position
it might be waiting for the next Physics frame to move it
or cheese it fix and disable the renderer until that frame is hit
still does it but its less noticeable. the main part i can see is the trailrenderer on the hands and feet so i might just disable those
It says retry, it gives like a connection error
You can use a Coroutine and probably do what i suggested of starting it with disabled renderer and then do yield return new WaitForFixedUpdate
wth..are you using a normal discord client?
oh these are phone photos..oh dear.
No idea, like I use discord at the phone
Sorry, do you understand?
why don't you use it on your PC and you know. screencapture like a normal person lol
https://screenshot.help
also see one of the colliders is still trigger
regening project files did not fix my problem
ok but what about the question you replied to?
this is the only assembly file i have
You seem to have an error in LapDetector
Is that what you're working on now?
can you show where this asmdef is in Project
the one just called scripts
not sure how they work, just blindly followed a guide for that
then don't use it
i need to have tests for the asignment
so im kinda forced to have it
Best read up and follow a guide properly, instead of blindly 😄
they are useful for compartmentalization but also isolate assemblies
how do you locate a "NullReferenceException: Object reference not set to an instance of an object" in the hierarchy?
which is what is happening now
all your scripts are isolated from TMP and other assemblies not linked
the stacktrace tells you which class it happens on, and clicking it usually pings the game object
fair point but i just need to get the project done for a deadline and would just like to be able to use TMPro in my code
it's not doing it to me
Does it say it is from UnityEngine or mention Graphs?
@lucid jetty stick to this channel if you need help. You're more likely to find the help you need. Also, try to clarify your problems out and debug if possible.
https://docs.unity3d.com/Manual/ScriptCompilationAssemblyDefinitionFiles.html
takes one look at the docs and tells you everything 🙂
(including adding references)
graphs
Then it is an internal unith error
You can ignore it.
It is from windows inheriting from Graphs. Like the Animator or ShaderGraph
You can close those windows and restart Unity if you want to get rid of it
Im really not try change anything about the assembly definition, all i want to do is figure out why i cant use textmeshpro
how can i make nice and snappy movement with rigidbody? right now its just sliding everywhere
Hey i am facing a problem. I want to change the direction and fov from vr cameras within the meta sdk. Right now i am playing around with render textures but actually id like to avoid that
it doesn't allow me to play some of the animations that are in play during the game
It was already explained to you, it isolated your scripts from TMP and other assemblies
Simply add the TMP assembly reference to the list
That sounds like a separate issue.
Try closing the windows and restarting unity though, to be sure
Because your asmdef currently says "only use the code under this asmdef" .. if you want to use TMP, then you have to reference the TMP asmdef in yours. Readin the docs ages ago would have gotten you this answer
Alright, thanks 😊
it seems the error appears when I click on a specific button
solved
don't know why it was giving that error
Yeah, it is a weird one. But it is surprisingly common too
thanks for the help!
Btw your issue is clear.
Your one collider is Normal collider but your other is trigger
from the screenshot
OnCollision doesn't get called on dynamic rigidbody with normal collider in trigger.
only 2 solid collider
anyone know what i can do here?
snappy and rigidbody is funny
Are you using AddForce?
How about GetAxis?
Both of those will slide you around. Both together makes it worse
Use Velocity and GetAxisRaw
Or kinematic as nav said
addforce is taking into account your mass btw
if you .velocity for example which overrides the mass you notice its more "snappy"
also drag amount and physics material matter a lot (with dynamic rb)
i did a dirty fix by just making the drag big and increaseing the add force
but i'll try velocity
ah yes found it.
And what about the movement? How do you get input?
new input system
movement is a vector 3 that is set by an input event
velocity works well, thank you
what is kinematic rb? luckily i dont have to make jumps in my game so im fine
this used to be a paid asset
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
using velocity makes the character fall extremely slowly for some reason
yea because now you're overriding forces each frame
ah
including physics gravity
does kinematic work with gravity?
you make your own MovePosition but you can achieve the same effect
i found the code on unity forums once lemme see if I can scoop it
var positionOffset = (Physics.gravity * gravityScale) + (direction * speed);
rb.MovePosition(rb.position + positionOffset * Time.fixedDeltaTime);```
Original
```cs
var positionOffset = (Physics2D.gravity * rb.gravityScale) + (direction * speed);
rb.MovePosition(rb.position + positionOffset * Time.fixedDeltaTime);
that would be good, thanks
Kinematic means it will not respond to forces, so no, you do it yourself
For velocity responding to gravity, you need to set the y velocity to the rigidbody's current y velocity, then it will work right
i just fall through the floor is this normal
do you have colliders ?
yes, this is my code
hmm try starting it a bit above ground maybe ?
last time I tried that code it was working so pretty sure it should
yeah still through the floor
i might just stick with rigidbodies tbh
i mean like
kinematic
are you not using that on kinematic?
maybe MovePosition doesn't care about collisions in 3D
i tried the forcemode.velocitychange thinking it was the same as changing velocity, but it made the character so fast
velocitychange says is time independent so you probably needed fixedDeltaTime in there
what about the character controller component?
what about it ?
could i achieve snappy motion like that?
if it doesnt use rigidbodies
sure plenty of people use that.
its the same principles as kinematic rigidbody
i'll have a play with that than
hey guys.. If I have a list, and I use that if: cs if (_enemyList.Count < 30) if I have more than 30 elements inside my list it should not go inside the if right? I created a debug log and even when I have more than 30 it goes inside the if. what I am doing wrong?
fully admitting that i asked chatgpt for this... but how can i make my player face where theyre moving? i want it to be smooth which is why i tried slerp, but for some reason it just faces the world origin. with rb i just used moverotation
Show the rest of the code. You are right that it should not
ok, well there are too much things happening, too much code jsut wanted to check that info .. i will figure it out.. thank you a lot. you also answered me in another channel will check now
because gpt is stupid and doesn't know any better
nvm i fixed it on my own
that's def not how you lerp
I found the prob ty
i dont understand the problem
it works the way i want it to
wait i just read it
i still think its okay enough, like i cant use smoothdamp for my purposes
and idk if a tweening library is necessart
i have some code that updates this text based on the number stored in another variable, how would I make the variable amount display but also display a certain amount of 0's in front like in old arcade games?
if you t ink thats still correct
ヽ(。_°)ノ
im happy to change it but
string myString = $"{scoreAmount:0000}"
does this work if the variable is a float?
should
thanks much
do you know why my jumping is really delayed sometimes?sometimes its instant, which is why i find it weird. the inspector shows the player is grounded at the right times
wdym by delayed
isGrounded i bet is the issue
its very opinionated when it considers itself grounded xD
i'll press it, sometimes it will do it, sometimes it wont
Debug.Log, but likely it's the groundeed check yes
thats weird lmao
you have Collapse on
so it's impossible to tell when it's grounded and not grounded
especially inside the OnJump call
you're not logging it where it counts
you're probably logging it somewhere else
Do you know how CharacterController.isGrounded works?
It has a very specific, very predictable method of working
The last time Move was called is what matters
and if that move call pushed it into the ground, it will be true
otherwise, false
@rich adder i have no idea why this might be happening
uh show current code
{
string scoreString = $"{score:000000}";
string killsString = $"{kills:0000}";
string stardustString = $"{money:00000}";
moneyText.text = "Stardust: " + money.ToString(stardustString);
scoreText.text = "Score: " + score.ToString(scoreString);
killsText.text = "Kills: " + kills.ToString(killsString);
}```
Should I just use my own grounded method then?
I had one when I used rigid bodies
I think it's still in there
probably
is the score 4000 when you showed that?
its set to 4000 through the editor yeah
you're doing score.ToString(scoreString)
you should just be writing scoreString
ahh yes good catch
oh duh
i can just do scoreString?
just do killsText.text = $"Kills: {kills:0000}";
for example
no need for the extra variable and secondary concatenation stuff
oh that makes sense
scoreText.text = $"Score: {score:000000}";
The one Unity does in their proper TPC/FPS controller
private void GroundedCheck()
{
// set sphere position, with offset
Vector3 spherePosition = new Vector3(transform.position.x, transform.position.y - GroundedOffset, transform.position.z);
Grounded = Physics.CheckSphere(spherePosition, GroundedRadius, GroundLayers, QueryTriggerInteraction.Ignore);
// update animator if using character
if (_hasAnimator)
{
_animator.SetBool(_animIDGrounded, Grounded);
}
}```
very simple stuff but does major difference in detection
public class MovingPlatform : MonoBehaviour
{
public float speed = 1;
[SerializeField] GameObject[] waypoints;
int currentWaypointIndex = 0;
private Vector3 lastPosition;
public Vector3 direction => waypoints [currentWaypointIndex].transform.position - transform.position;
// Update is called once per frame
void Update()
{
if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
{
currentWaypointIndex ++;
if (currentWaypointIndex >= waypoints.Length)
{
currentWaypointIndex = 0;
}
}
// Move towards
transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
lastPosition = transform.position;
}
}
Anyone have any idea why this cube of mine just keeps going forever in one direction?
I wanted it to go back and forth between the two waypoints
parent position is affected by its children and the children position are modified by the parent when the parent move
circular dependency
https://gdl.space/itonaniciq.cpp
Anyone knows why this doesnt work?
Not without knowing what "doesn't work" means
That does work
Make sure the physics message actually gets triggered
Ah ok, so the issue is just the if statements then
why are you storing collider anyway lol
public Collider hit;
public Collider headhit;
to know if it was a body hit or a headshot
you should at least use tags
What gameobject is target on?
checking exactly which collider you hit sounds fine to me
Where are the tags
ig depends whats selected in the colliders
On the target?
so other is a bullet
Unfortunately, you can't ask what your collider was in a trigger message.
unlike with a collision message.
but all is not lost: you just need to use separate game objects
What fen is saying is why I asked
Give each part of the target a separate game object with one or more colliders
You'll put a component on each game object that reacts when hit.
kk ill try it
Maybe each one can have a float that says how much damage is caused when it's hit.
btw slight optimization not related to your issue.. @cinder plover
not set transforms individually and use this
https://docs.unity3d.com/ScriptReference/Transform.SetPositionAndRotation.html
that method name is a mouthful
i often avoid using it just because it's so annoying to look at
I told someone to make a bool yesterday, and they named it isLowPriorityDestinationCurrentlySet
lol must be really useful if they went ahead and made one for Local too
https://docs.unity3d.com/ScriptReference/Transform.SetLocalPositionAndRotation.html
there is also the Get equivalent
https://docs.unity3d.com/ScriptReference/Transform.GetLocalPositionAndRotation.html
sounds like a proper C# developer to me
I wonder what the efficiency of it is , i never benchmarked it
I just blindly trusting unity on this one
imagine we were still working with limited variable name sizes.? how would you even shorten that xD
bool goodLuck
xD
lpdcs
oh my. that would be a curse
printer on fire.
So I'm running into an issue in my scene, where I have an interactable object I can pick up and put down. I'm handling both the 'pick up' and 'put down' functions with raycasts. Only issue is that, because I'm playing the object at RaycastHit.point, my object is always going to clip halfway into wherever I place it. Any tips or ideas? I tried looking online for an answer and all I got was this vdeio https://www.youtube.com/watch?v=BNOAeQqXgg0. Which is ALMOST like the issue I'm haing, except I'm trying to fix this at runtime and not in the editor. But it is a good visual representation of what my issue is.
More often than not, when we're placing objects in our scene we want to place them on the ground. This can be tricky to get exactly right when positioning manually, so in this quick tip we'll look at a feature of Unity that does this for us automatically.
If you prefer written instructions you can find a link to the text version here - https://...
must lpdc my lpdcs
can anyone explain to me why unity doesn't let me put this in an if statement?
(Vector2.Distance(inputManager.prevDefinedMovementInput, inputManager.movementInput) < 1f || inputManager.previousMovementInput = inputManager.movementInput)
it says:
operator can not be applied to 'bool' and 'vector2'
but what does it matter? im only checking if one of them is true..
I would suggest shooting a raycast from under the floor
Compare the hit point to the center of the object. Offset the object by the difference.
you're using = instead of ==
I might not be understandng, wouldn't the difference always be zero?
specifically, offset it by the differnce after running it through Vector3.Project, kind of like this:
Vector3 placePoint = // do your first raycast to decide where it goes
Vector3 bottomPoint = Vector3.zero;
if (Physics.Raycast(placePoint - Vector3.up * 3, Vector3.up, out var hit, 5f, LayerMask.GetMask("Item"))) {
bottomPoint = hit.point;
}
Vector3 correction = placePoint - bottomPoint;
placePoint += correction;
This would be a second raycast.
yeah thats similar to what i used already
OHhhh. I think i see wym
I kept thinking of my object as a single point and not as a whole thing with bigga^^ collision box. Yeah that makes a ton of sense
you want to place it at the red X, and you do
then you shoot a ray to find the blue X and offset by the difference!
no prob (:
The physics should behave properly. You'll move the object (and thus its collider) twice instantly
So it won't go flying after clipping into the floor from the first move
https://gdl.space/rafequfeye.cpp
I changed it to game objects but it still doesnt work :(
I think you'll want to set the transform directly for the first move
Then set the rigidbody position for the second move
that's not what I meant.
Cause I could using something like this to visualize my problems
this and hit can't possibly be equal; they're unrelated types
my suggestion was to put the regular and head hitboxes on two separate gameobjects
nvm I just realized that is an IOS app
it's Notability, yeah
i did that
Okay, so you should have a "Target" component on both objects, too.
I could kiss you
Each one will respond to trigger messages caused by its own colliders
So Target would only have one damage number prefab (you'd assign a different one for the head target and the body target)
Each one would just say "i got hit, so spawn my damage number prefab"
using UnityEngine;
public class PlayerMouseLook : MonoBehaviour
{
public float sensitivity = 2f;
public float verticalLimit = 80f;
private float rotationX = 0f;
void Update()
{
// Mouse Look
float mouseX = Input.GetAxis("Mouse X") * sensitivity;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity;
// Apply rotation to the player around the Y-axis (horizontal)
transform.Rotate(Vector3.up * mouseX);
// Apply rotation to the camera around the X-axis (vertical)
rotationX -= mouseY;
rotationX = Mathf.Clamp(rotationX, -verticalLimit, verticalLimit);
// Apply the rotation to the camera (not the entire player)
transform.GetChild(0).localRotation = Quaternion.Euler(rotationX, 0f, 0f);
}
}
My camera is rotating left/right instead of looking Up or Down
which object has this script ?
I have this third person camera that rotates around the player and moves up and down as you move the cursor:
pitch = Mathf.Clamp(pitch + -Input.GetAxis("Mouse Y") * sensitivity, minPitch, maxPitch);
Vector3 pos = Target.position;
Quaternion rot = Quaternion.Euler(pitch, heading, 0);
pos += rot * (Vector3.back * distanceToTarget);
transform.position = Vector3.Lerp(transform.position, pos, Time.deltaTime * smoothing);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, Time.deltaTime * smoothing);
the problem is I want the camera as a child of the player so it moves with the player, and the way I've coded it resets the camera position every frame, overriding the parent/child positions setting
how do I fix this
why are you controlling the camera's position at all in this script?
because when I move the cursor a certain amount up or down, I want the camera to move up or down
so that it rotates around the player
just to make sure can you show your gizmos in local space for the object that holds the script, in scene view
You should just be dealing with local positions, not world positions
yes exactly
let me try that
oh god
Note that - Vector3 pos = Target.position; will need to be converted to local space too
it's unclear what Target is exactly
im still fairly new at this can you elaborate?
yes
thats why when you rotate you going sideway
Red - X - Right
Green - Y - Up
Blue - Z - Forward
your forward should be Blue
Those are the three axes.
oops lol. Im soo dumb haha
common issue 😏
When you have the scene view in "Local" mode, you'll see the handles (e.g. the arrows in your screenshot) lined up with the local axes of the selected object
the reason why I did that was because the camera icon
shows a "window" facing forward
see like a TV
Perhaps your camera is on the wrong side.
yup, make that camera frustum face the same direction as blue
The camera should be looking in the direction of the capsule's blue arrow.
It should have no rotation around the Y axis, as a result
well having correct gizmos is priceless in time saved later
TY for the the advice
Yes, you should get a good grasp of how things are oriented and positioned
I rarely have to "guess and check" anymore
im used to the war thunder CDK gismo being the red line as the front so yeah my bad
in 2D generally Red is "Forward "
(technically right in unity)
but topdown you can also make Up your forward
yeah, Vector3.forward points into the screen if you put your scene view into 2D mode
Ok i did that it works, but now melted plastic is coming out of my vr headset
i hate when that happens
same
is it overheating and lagging?
he created an infinite loop I think
lagging his headset to death
when the bullet hits yeah
and crashes
does it activate multiple times or something
Show your new code.
are you recursively doing something?
I can't guess what you wrote!
@rich adder it works yayyyy
Perhaps spawnedNumber has a collider on it?
TY
nope
np!
You're unconditionally spawning a number every time anything sets off your trigger collider.
it's so close, but there's still a problem when I try to walk. the walking transform.Translates the parent, (which is what Target is) and somehow that makes the whole thing go out of whack.
pitch = Mathf.Clamp(pitch + -Input.GetAxis("Mouse Y") * sensitivity, minPitch, maxPitch);
Vector3 pos = Target.localPosition;
Quaternion rot = Quaternion.Euler(pitch, heading, 0);
pos += rot * (Vector3.back * distanceToTarget);
transform.localPosition = Vector3.Lerp(transform.localPosition, pos, Time.deltaTime * smoothing);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, Time.deltaTime * smoothing);
should I be using localrotation too?
the walking transform.Translates the parent, (which is what Target is)
I have no idea what this means tbh
what is target? Which object?
oh sorry
it's the player/parent?
I have a player gameobject with its own script that calls transform.translate when it walks. that object is the value of Target in the camera script
and is also the parent of the camera gameobject
You don't need to ever do Target.localPosition
that's nonsense anyway
Vector3 pos = Vector3.zero; would be correct here
transform.localPosition is in the coordinates space of its parent
so Vector3.zero would be the parent's location in that coordinate space
How do I rotate the gizmos of an object without rotating the object itself
what are you trying to do?
you probably need to parent the object to an empty object
its causing the rotation of my gun to be wrong
That would be preferable, yeah.
Or yes, use an empty parent
But you might need to use an empty parent anyway
oh wait, actually it's like this:
where the camera script is on player_camera and the rigidbody/Target gameobject is capsule
e.g. to adjust the exact position the gun sits at
I almost always wind up setting up objects like this:
- Gun
- Model
that's what you said before, no? Target is the parent
so I think that's why I was doing target.position
the model is not the root object
i dont have blender so il do the empty parent trick im too lazy to do blender, its more of an @ home project thats not gonna be published anywhere
ok just checking that it doesn't need to be localpos
in this case, everything I said here is correct: #💻┃code-beginner message
no it's not. got it
I created an empty parent, fixed its orientation and its doing this
non-uniform scale!
A parent of that object has a scale with uneven values.
This will cause skewing.
1,1,1 on both the parent and the cutter itself
whats busted
Oh wait, I didn't read that properly.
I thought it was stretching.
It's just rotating around the wrong axis.
Are you rotating PlayerCamera, perhaps?
pitch = Mathf.Clamp(pitch + -Input.GetAxis("Mouse Y") * sensitivity, minPitch, maxPitch);
Vector3 pos = Vector3.zero;
Quaternion rot = Quaternion.Euler(pitch, heading, 0);
pos += rot * (Vector3.back * distanceToTarget);
transform.localPosition = Vector3.Lerp(transform.localPosition, pos, Time.deltaTime * smoothing);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, Time.deltaTime * smoothing);
this calls on the camera script
I think so. Original rotation works peroperly on the "player"
Look in the scene view as you look around
you can grab the game view window and move it to the side
without the edited gun script, the gun will rotate left and right with the player
but il look up and down and it will just stay where its at
@wintry quarry do you think the reason it's getting messed up when I move has something to do with the distance calculation that I do in start()
distanceToTarget = Vector3.Distance(transform.localPosition, Target.position);
I undid the broken script and this is where its at now
ah, right: the gun follows you looking left and right, since that rotates your whole body
How do I get it to look up and down too
You could parent it to the camera, or you could separate logic to rotate it up and down
parented it to the camera it works
yayy
youwouldn't use localPosition for this distance calculation
.position would be correct
private void Start()
{
pitch = transform.eulerAngles.x;
heading = transform.eulerAngles.y;
distanceToTarget = transform.localPosition.magnitude;
}
void Update()
{
pitch = Mathf.Clamp(pitch + -Input.GetAxis("Mouse Y") * sensitivity, minPitch, maxPitch);
Vector3 pos = Vector3.zero;
Quaternion rot = Quaternion.Euler(pitch, heading, 0);
pos += rot * (Vector3.back * distanceToTarget);
transform.localPosition = Vector3.Lerp(transform.localPosition, pos, Time.deltaTime * smoothing);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, Time.deltaTime * smoothing);
it's still doing this
perhaps it's the pitch and heading calculation?
or maybe it's in my player movement code
rb.velocity = Vector3.zero;
Vector3 camEuler = cs.transform.eulerAngles;
camEuler.x = 0;
Vector3 moveDir = Quaternion.Euler(camEuler) * new Vector3(direction.x, 0, direction.z).normalized;
transform.Translate(moveDir * Time.deltaTime * speed);
float targetAngle = Mathf.Atan2(moveDir.x, moveDir.z) * Mathf.Rad2Deg;
float angle = Mathf.SmoothDampAngle(player_capsule.transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
player_capsule.transform.rotation = Quaternion.Euler(0f, angle, 0f);```
I think maybe when I change player_capsule.transform.rotation
it's messing it up
I highly recommend just using cinemachine e.g. Cinemachine FreeLook rather than writing this yourself
Also yes you're mixing up Rigidbody motion with Translate?
That's a recipe for disaster
oh do those not play nice? i was gonna do translate when grounded and rigidbody when airborn
that's why I have rb.velocity = 0
why not? it hasn't caused problems yet
so the rigidbody should be on the parent gameobject?
and then I should use rb.move or something
for player grounded movement
if you're using velocity or force for jumping/air movement then you'll want to do the same for ground movement
ok
what is this error?
It says the error,.
A NullReferenceException on line 109 of PlayerMovement.cs
okay i will check
wait but at line 109 isnt anything like speedcontroll
line 109 should be within the SpeedControl method
which method is line 109 in?
Huh?
that's absolutely inside SpeedControl...
your text object is null. also configure your !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
• Other/None
Also yes your IDE is not configured, that's going to make your life quite difficult
how do i configure it?
by following the instructions you were just linked
and im sorry im bothering im VERY new to c sharp programing
oh i didnt even nocided that thx!
Hey guys, Im having trouble with Vector3.MoveTowards. This is my code but the gameobject is going somewhere completetly different instead of following the player
wdym by "somewhere completely different"?
Also this code is framerate dependent
it will move at different speeds depending on your current framerate
@wintry quarry got it working and changed everything to rigidbody. ❤️ appreciate you
(In the black) The purple game object is supposed to follow the orange player (In the white) but instead moves somewhere else and I don't get why
I would guess it's not referencing the correct object
how did you assign the player reference?
hello, i am struggling with a problem that is tough to find why it's happening. basically, what i'm trying to do is a fog of war effect where i have a 2D tilemap over top of another tilemap and based on the location of the player, set some tiles to null in the fog of war tilemap that shows in the full screen map.
the problem is my code works fine in the editor, and all the expected tiles are disabled. however, when i run the code in the windows build, it will not work the same. it will disable tiles fine, up until the first time i open up my full screen map window. then it will not disable tiles anymore. the full screen map window has a RawImage that points to a RenderTexture which my Camera is rendering to.
i would appreciate any help to understand where the problem might be.
my code in Update
Vector3Int playerCellPos = currentGroundTilemap.WorldToCell(playerPos);
for (int x = -revealRadiusX; x <= revealRadiusX; x++)
{
for (int y = -revealRadiusY; y <= revealRadiusY; y++)
{
Vector3Int tilePos = new Vector3Int(playerCellPos.x, playerCellPos.y, 0) + new Vector3Int(x, y, 0);
var tile = currentFogOfWarTilemap.GetTile<Tile>(tilePos);
if (tile != null)
{
currentFogOfWarTilemap.SetTile(tilePos, null);
currentFogOfWarTilemap.RefreshTile(tilePos);
UpdateRenderTexture();
}
}
} ```
@wintry quarry
ok but
where did you drag TankPLlayer1 from?
Is it a prefab?
Or is it the player in the scene?
BTW there is no need for self references or transform references.
you can get your own GameObject with .gameObject and the Transform with .transform
Tankplayer is a prefab, but I am dragging it from the heirarchy
you can also call GetComponent on any component, including this
Things in the hierarchy are not prefabs
Prefabs only live in the project folder
Show exactly what you dragged into where? Because I think you're referencing the prefab
yep
Thanks for the help
So you're moving to the prefab's position, which is likely 0
It was something else but yea
I can't drag the object from the hierarchy into the inspector now 💀
because prefabs can't reference scene objects
How do I make it so the prefab follows the player then?
You have to give the enemy a reference to the player after you spawn it
simple example, for a spawner script that does it:
public Enemy enemyPrefab; // assign in the inspector to your enemy prefab
public Transform player; // assign in the inspector to your player in the scene
void SpawnEnemy() {
Enemy newEnemy = Instantiate(enemyPrefab);
newEnemy.player = player;
}```
works in editor, doesn't work in build examples. the player would be centered in the middle of the screen, so i expect that it would remove the appropriate fog of war tiles as the player moves.
exact same code, and i've debugged to check that it's executing the same SetTile(null) code, but for some reason, my render texture isn't updating with the latest tile data from my camera
I see
i would recommend using a debugger to step through the code to see what is actually happening in your build
https://unity.huh.how/debugging/debugger
thanks for replying, i definitely did attach the debugger and stepped through the code to see that it was setting the tile to null as i expected.
but the problem is, when i set a tile to null in the tilemap, somehow the change does not propagate back to the camera render and subsequently to the render texture that is shown in my RawImage in the UI
Also, is the Enemy class actually a thing or was it an example? Because I used GameObject thinking Enemy was an example and got this
'GameObject' does not contain a definition for 'player' and no accessible extension method 'player' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
it was an example
Ohhhh
btw you can do Quaternion.identity instead of Quaternion.Euler(0,0,0)
ahh gotcha
my bad
ahh right because the prefab reference was an Enemy object not a GameObject
Instantiate is a generic method that returns the same type you pass to it as the first parameter. so if they pass an Enemy object as the first parameter then it returns an Enemy object
yeah i misread the code oops
removed the stupid comment
You probably need to reassign the player variable of the 'MentosMinionController' script in the inspector.```
MentosMinionController is my 'Enemy' class btw
show the c ode
If you're doing this the player assigment stuff needs to be in Start not Awake
but realistically
Hi! I need help please!
So, this is my character roster
whenever I press Shift, the present character gets disabled and I control another one
its all fine except for the animations
when I change controls while running the disabled script character keeps doing the run anim
sounds like you aren't updating parameters when you disable it. of course you haven't shown any !code so that's just a guess
📃 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.
I will send it
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You only change the animation state in Update. Update does not run on disabled components
which void can help me?
a void is nothing more than a return type for method...
sorry, I meant function
Take a look at the docs for MonoBehaviour and see which one lines up most with what you want to do
alright, will try, thanks!
So the gizmos are incorrect causing me a boat load of issues. I opened the gun in blender, how do I fix the gizmos?
im in blender
Z forward / Y up. in Apply Transform
I did not say press Z. I said when you export Apply Transform with following settings #💻┃code-beginner message
aaaah gotchya
Got it thanks! lets reimport.
axis is still busted
Try this on the mesh import settings
try this @hot niche
are you exporting FBX ?
this isn't code question btw. next time goes in #🔀┃art-asset-workflow
oops il go there sorry
im doing, File export
that doesnt answer
im exporting .obj
ok so you didn't follow what I said..
OOOH i see, export the file as .fbx
Me and my artist spent a bit of time to make Unity look the same as in blender. There are different ways to do this but you might be interested in our setup. This was based on the blender axis and not on the unity ones.
you should also make sure this isn't just an issue of your tool handles being set to Global instead of Local
All our models look at Unity's Forward Direction (Z in Unity and -X in Blender).
Hello I have a question about character movement
my character movement is functional but when I use a jump it doesn't work while the character is moving
and the code that makes the character fall down faster also don't work well while the character moves
I'm using the unity input system
it reads a 2d vector of wasd movement and applies it
to the rigid body
in a fixed update
You'll have to show the !code, I'm gonna assume though this partially due to manually assigning velocity and the drag on the rigidbody causing it to hover
📃 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.
what would you reccomend
i only just started a day ago
and there's impulse and a lot of other stuff
didn't wanna go with transform.translate tho
Yes you are overwriting the velocity, so the vertical velocity is basically ignored. You should make a Vector3 that stores what the combined velocity should be, then assign that to the rb velocity
Im not a fan of using addForce to move the player, unless you need the player to really react in a physics based environment
i see
should i keep a private variable in the head then
just storing the player movement
forceDirection += new Vector3(move.ReadValue<Vector2>().x, 0f, move.ReadValue<Vector2>().y) * movementForce; here sets it to 0
so that's the overwriting
I would, but only because you would directly assign that global vector3 during the new input system methods. Not because the method particularly needs it
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 0f;
private float xRotation = 0;
public Transform playerBody;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
```whys my sensitivity so god damn high
ive tried 100f, 0f, 3f
try 1
and make sure you're changing it in the inspector, not just the field declaration
slightly better for some reason
alright
ah that fixed it for some reason - changing in the inspector
well you weren't actually changing it until you did that
Question:
I have the above visual code that detects movement along a 2d player character based on left or right. I want to make it so that it flips my character to face the way that he is moving. IE) if he is moving left he is facing left and if he is moving right he is facing right.
How would I go about doing that with the current setup I have in visual coding?
oh, how come? surely i was changing it in the code no
Inspector takes precedence
interesting
Unless you do it in a method like Start or Awake
oh
spriterender has flipping methods so get the direction from velocity and decide when to flip
If the code took precedence then there would be no point in the inspector
How would you set two enemies to have different HP for example
I just assumed that once the game is ran the script runs from the start too initialising the variables to what you have set
It does, and then Unity replaces that with the serialized values from the scene or prefab asset
ohh right
So what would that look like with visual code? What node am I going to grab to attach to the Rigidbody 2D set velocity node
I wish I could just normally code it
Visual scripting uses all the same stuff as regular scripting
it's just... visual
but all the properties and functions are the same
So if you want to use flipX on the SpriteRenderer for example, you do exactly that
the main thing I'm struggling with is getting it to link to the velocity
well that's a property of the Rigidbody2D
Specifically due to the fact that this script uses GetAxisRaw instead of normal inputs
In what way is GetAxisRaw not normal?
It is I've just never used it before, we started with 3D not 2d so we were using actual button inputs
I think they mean they had UI buttons that triggered events
I mean that we used getkey
Oh
And so I could just attach the flipx to those
Well it's exactly the same then
GetKey returns true or false
GetAxis returns a number
otherwise it's not much different
(and also has nothing to do with 2d or 3d)
Yeah, sorry I was flippant with my response. Not exactly the same.
It's just not gonna be different enough that it should be an issue
I might just be having a brainfart honestly but this is what it looks like rn
Convert to a bool condition like if (Input.GetAxisRaw("Horizontal") > 0);
Instead of it already being a bool
usually you use GetAxis when you deal with analog controls because it's not just a true or false
I mean, it can be if you want to implement it that way
yes
so it will certainly be a check of > 0 or < 0
Character movement is not an issue just the orientation of the facing
see what you're doing with the velocity?
getting the y part
do the same thing
but get the x
and then feed that into a comparison node
see if it's > 0 or < 0
and face right or left based on that
You could do it either with the velocity or with the horizontal input axis. Up to you
So like this
something like that yes
doesn't it need to be lit up to work too
I hav eno idea I don't use visual scripting
I think its because ur missing Input from rigidbody
Don;t you need to set that to happen in Update for examplke?
is this needs to be connected to something no?
The other one isn't
no but it has the On Update thing
where's the entry point to all this
right now you're not telling it WHEN to run this code
maybe? Is that even possible? Can it be attached to the same one? Again I don't know how VS works
Just one big massive brain fart
oh I see
man who knew 5 lines of code required so much work
pretty sure you don't need two set flip Xs
you can just feed the bool directly into the value
nor do you need the if
mostly me being sleep deprived and dumb dumb
Yeah I'm removing them now and testing it
I think it's mostly node-based code being wild and difficult
How do I disable player movement without accessing the player movement script?
Could be that too
Impossible to answer as asked
That was the last thing I needed too
How does it move? Rigidbody? Transform? The animator? Is it in Update or Fixed update or using callbacks?
For that project anyways
I can see the use of this stuff, but it would be nice to just inject some c# code in places
Not allowed, has to be ALL visual scripting
https://hatebin.com/qcwkblqllg
it detects being grounded perfectly fine, but it only jumps id say 1/4 of the times i click the space bar which is odd
so it must be something with the playerVelocity.y
🥲
Though huh it doesn't stay facing the last way it always defaults back to being facing the right
i've tried setting the y value to the rigidbody velocity but that just infinitely adds more jump height to the character
the motto of any Visual Script
Are you adding or setting the velocity?
So you have to access the player movement script?
https://paste.ofcode.org/vNdEiPPEFqGEMMfJKH3Yhj
adding an impulse force to the rigidbody based on wasd input from input system
How did you get that from what I wrote?
#💻┃code-beginner message
but the jump gets overwritten or messed up
The player has rigidbody attached
You have addforce in at least three places.
Also why set that movement vectors y value to 0 when you just add back in the y velocity again immediately after?
It has it attached. But is that how you move?
And what about the other questions? (About where the code to move is)
there's just one add force
the move() was meant to just handle movement but now i'm trying to add jumping and it's not really meshing well
Sorry, I meant three places you modify movement. One addforce two velocity
yeah
so the movement adds the force of the x and z
based on input
and when spacebar is pressed the velocity upwards is increased
how would you reccomend
implementing
the jump/movement
im watching this tutorial for sprinting and crouching, and the dude is using a rigidbody for his character and not a CC. How can i change this code he wrote to work for my CC?
sorry if its a dumb question this is my first time doing game dev and even using c#
well they wont work the same

