#๐ปโcode-beginner
1 messages ยท Page 567 of 1

is this where i ask for help?
they both have their pros and cons
!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
kk I'll stick with the character controller
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/CharacterController.Move.html
btw the Move method has example on how to make your own gravity / vertical speed
Yeah i've done the move thing simple move was in desperation of trying to fix the isgrounded lol
many ways to do a ground-check.. just in case u want to chose another..
better ways.. if its feeling "***cked"
is grounded works fine when its Moving since it checks when it last moved, i just dont know what typeof query it is and its not very reliable doesnt have a good forgiving "slack"
well I can promise you the docs on it won't tell you shit lmao
I have a mechanic where the player can switch between two bodies, but when they switch bodies, the body not being used gets stuck in the animation they were in before switching. I want it so when they switch, the idle body goes into its idleanimation. what's the best way to tackle this problem?
Its like one sentence
and the most overly complex code example i've ever seen for a doc page with one sentence
u may even want to add a forgiveness timer.. like coyote time
you have to show how you have things setup currently, not much we can go on without seeing setup
but thats later on.. since ur only a few hours in
ye
jumping isn't gonna be a huge part of the game anyways
I'm making a horror game to start off
cuz roblox wise its easier game wise so I'm gonna do that for unity
textwalls ๐
dont just mindlessly paste code, use links for code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
copy n paste url's instead..
character controller script: https://paste.mod.gg/rgeulsbkeqxb/0
A tool for sharing your source code with the world!
I do got one question cuz docs don't really say I think
Do I still use a collider if I use a character controller
cuz the character controller seems to have a collider too but I saw a tutorial doing both
cool I figured
character swap: https://paste.mod.gg/abtctvqhwcgv/0
A tool for sharing your source code with the world!
shit tutorial
do be the way of youtube tutorials is what i've discovered with roblox
so whats supposed to happen when you switch back?
anyways thanks for the help i'm gonna see what I can make
god my variable code placement is disgusting
wtf am i looking at my eyes hurt
fun fact, but it is 100% redundant to prefix variables with player on a class called PlayerCode. we know those variables are for the player
That script is doing way too many things
oh man.. you need a state machine
soo many bools you're gonna have many "in-between states" you're not going to want
what worse is that my player script is make out of 90% if statement
even worst it working great ๐ ๐
yep - you need an Enum not a bunch of bools
learn the state machine pattern
it will get rid of 80% of your if statements
and i'm afraid to it to you all
It's not that bad, but I'd probably split it up with groups a bit more and add some comments
it works by miracle then but you're pushing your luck , will not scale well
Well you're not afraid. I mean you came here to revel in the attention of people looking at your code.
god dame unity makes me want to have 3 monitors
you control the other player. My problem is that sometimes the character you switch from gets stuck in a running animation
not a bad idea
I live in a dorm desk isn't big enough :(
nas that just the tip but the whole thing is not
can you ever have enough monitors? I cant
more than 3 is crazy
statemachine would be preferred though if you do have a lot of bool checking going... but if it works for you, I'd just go with it until you realize the need to improve upon it
My problem is no matter how many monitors I have I am incapable or organizing my windows in a productive way
ok
accidentally sprinting while sitting ๐ฎ
I split ma legs!
just have to learn how to organize the script and it would be great for me
organize maybe dont cram so much stuff in 1 monolith as mentioned lol
regions can help make it look neat but wont cure the problem
is there a way to move your camera without holding right click
can I just make it where its wasd no matter what
its driving me insane
all those speeds variables can easily be a struct for Movement stats or whatever
thats already less clutter in 1 script
dont think so. ALso more of a #๐ปโunity-talk question
i understand and i should change it now before it become a big problem in the future because my player scripts have about 159 line of code๐
oh sorry
no rush, always make a git push before doing any such refactors
and if you're not using VC, you should lol
ah yes version control is savior
you have to ensure to make animation reset before doing the switch then
or maybe reset it after switch so you dont see any wonks
hard to say without seeing it
Can I send you a recording
Yeah but like how would I execute that
yea send it here as mp4
if its too big use https://streamable.com and send link
Is there a place to correct unity doc issues?
you cannot , you can only report from the doc page itself
its not a major issue but one of the code samples is just really fucking dumb
oh that sucks
kk
which one?
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);```
whats wrong with it ?
multiplying deltatime then multiplying deltatime again
then 16 gravity just becomes a stupidly small number
this is fine actually
its correct
you're not multiplying deltaTime twice into anything here
so I'm suppose to set gravity to a stupidly high number?
the only thing they should fix on that example code is the Move called twice instead they should've combined it into one call
no, a normal number like 9.8 will be fine
Watch "character switch game - SampleScene - Windows, Mac, Linux - Unity 2022.3.45f1 DX11 2025-01-06 23-37-39" on Streamable.
a normal number with that code makes you fall at a insanely slow speed
removing the 2nd deltatime makes it normal
read it again - it's not happening this way. deltaTime is being multipleid into something that's being ADDED to the velocity. The velocity itself is not being multiplied by deltaTime more than once.
ohh right yeah you want to switch that back to idle then before you make the switch
player velocity is though
it is not
playerVelocity.y += gravityValue * Time.deltaTime;```
gravityValue is being multiplied by deltaTime
no
wat
that's the one time playerVelocity is being multiplied by deltaTime
the second line
a = a + (b * c) does not mean a = a * c
gravityValue is being added to playerVelocity.y , and that(gravityValue) is being separately being calculated with T.dt
note the + sign
mp4 if you want to embed a video in discord
Due to some issue in your code that has nothing to do with what you posted above
Show it
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
if (playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(horizontal, 0, vertical);
characterController.Move(move * (speed * Time.deltaTime));
playerVelocity.y += gravityValue * Time.deltaTime;
characterController.Move(playerVelocity * Time.deltaTime);
}```
its the same code in docs basically lol
if (playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}```
i mean
the docs don't have this
it does
which is pretty obbviously causing it
I guess it also has grounded hto
prove it
Think about what that code is saying
so yeah I can see that
"if the object is falling faster than 0, make it fall at 0"
so that's clearly going to slow your fall
yeah that do make sense
The similar code in the docs indeed only happens when it's grounded, because they're just trying to make the velocity not build up like crazy when it's sitting on the ground.
I'm still hella confused on the deltatime thing but
deltaTime is very simple
Its the time between frames
playerVelocity.y += gravityValue * Time.deltaTime;
This one is the acceleration due to gravity. Increase velocity by n units per second per second.
characterController.Move(playerVelocity * Time.deltaTime);
This one is the actual movement.
Move the object by v units per second
think of them completely separaetely
because they are
I guess that makes more sense I think
I've never really messed with gravity ig before
Cool thankies
Ik I just forgot the + lol
important difference ๐
but I guess if the number if increasing I can see why the dt works
it changes things a lot from making x be really small, to making x actually grow
yeah if it grows that makes more sense
It might make things more clear to just like Debug.Log the values each frame
consistency is the main benefit
no no I understand now
It's really this
Its late i'm sorry coding brain rot is hitting hard 
flashed banged ๐ตโ๐ซ .
also not a code question
I assume logically I should cap how much gravity can increase so it doesn't just like eventually zoom you to mak 5 if you fall far enough
acceleration is gravityValue which stays constant
playerVelocity is velocity
and the position is the position
oops, sorry
just do little bit of reorganizing. Now it look better
i'm trying to make a draft idle game, how do I properly display the acquired resources / second?
i got this solution off an old video but it doesn't properly reflect the actual gain/second
We don't have enough context to answer. Presumably add the rate of increase from all sources of increase together.
the code you shared doesn't seem to have anything to do with displaying anything though.
The only other thing that happens in the entire script are a button that adds 1 to the counter variable every time you press it and those text objects to display it
mult1 is static as 1 so it doesn't do anything
Well yes the actual part where text elements is updated is what I meant
i would have figured since update runs every frame, that just by multiplying by 60 that would be an accurate representation but it's off as well
But you asked about:
how do I properly display the acquired resources / second
i don't see anywhere you are trying to do that
I see totalPoints text
mult1Text is resources/second
Games don't run at a fixed framerate
I don't see any code that changes mult1 anywhere
You said it's static as 1
doesn't that mean you only ever get 1 point per second
I'm confused about your code and also don't feel like I have enough context.
You'd think it does, right?
for whatever reason it doesn't
I don't know because idk what updateTime is
there's absolutely not enough context here to help you
okay okay
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
sure thing
Anybody?
is there a specific reason pastebin isn't listed despite being the most popular one?
because it sucks. it's riddle with ads and crypto scams
so as you can see counter stores the points, totalPoints is the text object to display them, mult1 would be an added increasing points per second that is currently fixed at 1, updateTime is the "refresh rate"
Why aren't you using Time.deltaTime
You need to use Time.deltaTime or your point counter is going to be framerate dependent
Basically mult1 does NOT mean points per second because you are not using Time.deltaTime
it means points per frame * whatever updateTime is
i mean am I not using Time.deltaTime? or rather how else would I use it
counter += mult1 * updateTime;
that is not Time.deltaTime
that is updateTime which is some unchanging thing you set in the inspector
Ok wait I see what you're trying to do
updateTime is just how often the points change visually
you can set it to 0.01 for it to be real time
๐ ๐
- it's not points per second right now. It's points per updateTime right now.
- setting the ticker to 0 is incorrect
because setting it to 0 means you lost fractional seconds
which will build up
so I should be subtracting something instead? not sure what
You also shouildn't be skipping the frames when the points are updated for the ticker
so at least 3 things are incorrect here
Oh also your comparison is backwards too ๐ฌ
wait are you sure?
because ticker is supposed to grow with time until it reaches the refresh rate
at which point it's reset back to 0 and the points are updated
You want something like this:
void Update() {
ticker += Time.deltaTime;
if (ticker > updateTime) {
ticker -= updateTime;
// mult1 points per second for updateTime seconds
counter += mult1 * updateTime;
totalPoints.text = counter.ToString("F1") + " points";
}
}```
yes I'm sure. Setting it to 0 is wrong
subtracting updateTime is correct
if (ticker < updateTime) doesn't make sense
well wait
ok I see what oyu're saying
sorry it's fine it's just
doing if/else was wrong
you should be increasing the ticker always
not skipping the update frames
public void Add()
{
totalPoints.enabled = true;
counter++;
}```
this throws a wrench in the works though
what's going on with this?
so that first line is jank. it's so the points only start displaying whenever you click the button for the first time
wasn't sure how else to implement it
and then counter++ is so even if you are gaining points per second, you can still manually click points in
ok as long as it's fine that those extra points aren't reflected in the points per second thing
that works great! thank you very much
another minor thing, that TextFadeOut function at the bottom sort of overlaps with itself when clicked very rapidly
Ok is this sortaish look like how a character controller is suppose to work
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
bool isGrounded = Physics.CheckCapsule(
characterController.bounds.center ,
new Vector3(characterController.bounds.center.x , characterController.bounds.min.y+.1f , characterController.bounds.center.z ) ,
0.18f,
3
);
if (isGrounded && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new(horizontal, 0, vertical);
playerVelocity.y += gravityValue * Time.deltaTime;
characterController.Move(((move * speed) + playerVelocity) * Time.deltaTime);
if (isGrounded && Input.GetKeyDown(KeyCode.Space)) {
playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
}
}
}
i can record what I mean if you need some visual
I don't even see where it's getting called in your code
Not from this script certainly
oh did I not include it
oh maybe it's commented out
yeah it's in AddMult1, commented out
it resets the alpha of a text to 1 and fades it back down to 0
but the thing is if I click it midway the fading out animation it won't restart the timer, it'll just play out the remaining fadeout
Actually for actual code help I have an issue where the shapecast is to far down so it stops my gravity from collecting so I VERY slowly fall but I also have an issue where if I fix that I can't jump off of slopes any ideas?
Aka the shape cast touches before my collider
but my attempts to fix that just- make it where I can't jump off of slopes
I guess I could set the gravity to 1 instead of 0
to a player I doubt they'd ever notice
do note that you are specifically not doing a cast, you are checking within a specific area
Oh
wouldn't a shape cast still have the same issue though
oh right its a query
but either way
use a sphere cast (because there's really no need to cast an entire capsule to check for ground)
and also make sure you use the physics debugger so you can actually see where your queries are
{
return Physics2D.OverlapCircle(groundCheck.position, 0.5f, Ground);
}```
is what I use
wait
you're probably in 3d
no?
a cast is more useful than an overlap circle, especially when handling slopes because you can get more info from it like the normal of the surface the character is on
I won't really need info in the long run for the type of game i'm making
But I do agree I need to shrink the area
i mean, unless you want the character controller to move inconsistently along slopes then you do need the normal. you would ideally be projecting your input or velocity on the normal to get the proper movement direction

I'm just making press space bar to jump rn lmao I'll figure out shape casting later on
I got error log: 'Collision' does not contain a definition for 'Game'
Honestly for now I might just raycast down
!code
also make sure your !IDE is configured
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
damn i guess it will only respond to one command at a time. here's the !IDE configuration ๐
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
ihttps://paste.mod.gg/witmyncdyapl/0
A tool for sharing your source code with the world!
yeah so get your IDE configured and check your spelling
Physics.SphereCast(characterController.bounds.center, .18f )```
Regretably trying to do a sphere cast
The error is
Argument 1: cannot convert from 'UnityEngine.Vector3' to 'UnityEngine.Ray'CS1503
but its... a vector3? the params want a vector 3????????
I can't find any spelling errors
ide configurated
screenshot the entire IDE window
what is an ide window?
Check the docs for the available overloads.
well your IDE is your code editor and you just claimed you configured it, so surely you would know what it is?
Nvm I figured it out thats the dumbest thing ever
did you realize you didn't have the correct parameters? or all of the required ones for the overload you wanted to use?
alright
I'm guessing it's telling you that there isn't any overload that takes a vector 3 and a float alone.
yeah
yeah the left screen wasn't necessary. but the spelling error is underlined, pay attention to it.
is it the gray highlighted one that is underlined?
You need to provide the other required arguments
errors are underlined in red
yes, is it GameObject?
Make me think I did something wrong
or gameObject?
obviously, yes that is the error
public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
where the first four arguments are required.
should I add space in between to make it Game Object?
no. if you think that is correct, then please complete the beginner c# courses pinned in this channel
i see, can I at least know what the code needed btw? is it like a variable or object define?
maybe I declared the public wrong right?
the guide told me to do this
it needs you to spell the property you are trying to access correctly. look at the relevant documentation and all of the other locations you access the desired property at
this code is correct. your code is not.
you should also maybe bother reading it too, and compare what you have with what is there
your code actually has two things wrong with it now that i take another look
it've red it and it's the same gameObject
it's literally not
there's another error now when i paste it in : <
there are beginner c# courses pinned in this channel that will cover the absolute basics, such as the fact that c# is case sensitive so gameObject != GameObject
considering the code you posted as a text file is missing the closing brace for the method, you probably do need another one. of course that entirely depends on what you copy/pasted and where
I dont think i have learned much from the unity learner
I will look into the C# doc you recommend ty
start with beginner c# courses, then when you understand the absolute basics of the language the junior programmer pathway on the unity !learn site is a good next step
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
wait I'm still confused even with the cast I have the same issue and I did debug it but then I lose the ability to jump on slopes if I don't wanna slowly fall should I just have gravity default state when grounded be 1 then? thats the only real solution I can think of
the only other real idea I have is just checking when the y stops decreasing at this point lol
Hello guys i would like to ask you something... so i got a top down 2d rpg game snap grip walk style and i got an enemy roaming int the map... but as he roams and im coming with my player next to him when roaming he does not collide with player but enter same grid cell, both players and challenger have box collider and rigid body.. could anyone give me some assistance?
Like there has to be like a real way to solve this rather then hovering above the ground lol
What does "snap grip walk style " mean?
I think its like snapping rotation and snap walking
ive just ticked the snap tp grip option at the scene, and its 16x16 gridcell , there is no way to move diffently.. like tibia
do you mean "grid"?
yes grid
ok if you're using a grid-based movement system why would you have colliders and Rigidbodies?
That sounds completely contradictory.
i got a solidObjects layer right for tiles
but for other objects the tutorial i was following showed me that way of collision
its easy to say when you understand and i dont mate
probably would be the grid-based
If you're using a grid based system:
- Use your grid data structure to determine if a square is occupied already or not to disallow moving into it
If you're using the physics engine: - Fully embrace that and move your objects using it and they will naturally not be able to overlap
There should be no "probably"s, you pick one or the other
grid for sure
i came form gamemaker so you would have mp_grid there
add the instances that are forbidden to walk in
In C# you could use a multidoimensional array (i.e. YourClass[,] or you could use e.g. a Dictionary<Vector2Int, YourClass> to track what's in each space
but still flunky u have to make checks to see if cell was completely empty and stuff
idk anything about gamemaker but yes sounds about right
you'd do something similar
basically keep track of which objects are in which grid spaces
and then you just check if the space is empty or not
That is one of the options I mentioned, yes
i will give it a look thank you very much
if you want to serialize it though multi-dimentionals don't work
so something like a List of lists would work, otherwise if you only need to build it then constructing it in Start() is fine
Umm, running into an error I can't make sense off. I have 2 classes:
{
protected IStateMachine DefaultState;
...
}```
Child class:
```public class SimpleBullet : BulletScript
{
DefaultState = null;
...
}```
I get an error that 'DefaultState' does not exist, but why? I thought protected meant that child classes could access the variable?
Exact error:
```The name 'DefaultState' does not exist in the current context.```
Are you accessing it in a function?
Oh it works if I do it in a function
I guess that makes a lot of sense, just threw me off
Hey I had set up the new input system and created a input actions asset. How do I reference the Input Actions asset with the actions I made in it?
#๐ฑ๏ธโinput-system
but also, there's a few different ways of doing it. (i would try and help but i barely know how the new input system works)
this is a code channel, delete your question from here and ask in #๐ปโunity-talk
Sorry
Hi, i'm beginner and when i put the line for the horizontalMovement the velocity is crosses out and i dont know why ? ( You can tell me in french )
Your code editor will show something crossed out when it is obsolete
put your cursor over the red line and read the error
je ne parle pas franรงais (traduit par google translate)
i dont speak french (translated by google translate)
@rich ice thank you ๐, @hexed terrace i try to put cmd for moove my character in game. I Read the red line but i learn by an video to have 6 years ago
Thank you all
can you click this button here and send us the error message?
pouvez-vous cliquer sur ce bouton ici et nous envoyer le message d'erreur ?
as a screenshot, not a photo
a window like this should appear
une fenรชtre comme celle-ci devrait apparaรฎtre
Yes, i'm sorry i do some research for understand my eroor and i understand a little beat
I try to do in screen shot i dont really know the method ahah.
Hi everyone,
I have a problem. My character starts jittering while rotating. The strange part is that this jitter only happens in the Game window, not in the Scene window. Any help would be nice.
@rich ice
The cosole tell me : CS1061 'Rigidbody has not definition for 'linearvelocity' and no access method 'linearvelocity.
CS1003 error syntax ','
I understand velocity is obsolete but i must pit Rigidbody2D for the script PlayerMovement
Show us the actual code.
The cosole tell me : CS1061 'Rigidbody has not definition for 'linearvelocity' and no access method 'linearvelocity.
i think that's just a unity 6 thing. i think you just have to change it to linearVelocity.y (i may be incorrect, i rarely use unity 6)
je pense que c'est juste une question d'Unity 6. Je pense que vous devez juste le changer en linearVelocity.y (je me trompe peut-รชtre, j'utilise rarement Unity 6)
yes, you have to use linearVelocity instead of velocity now
this is true for both Rigidbody and Rigidbody2D
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.

Please use a paste site for large blocks of code.
They do not send correctly on Discord when you just send the code directly, especially for mobile users
please, use one of the paste sites above. while i can read that code, i can also read house of leaves
lmao
""" public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public Rigidbody2D rb;
private Vector3 velocity = Vector3.zero;
void FixedUpdate()
{
float horizontalMovement = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
MovePlayer(horizontalMovement);
}
void MovePlayer(float _horizontalMovement)
{
Vector3 targetVelocity = new Vector2(_horizontalMovement, rb.velocity.y);
rb.linearVelocity = Vector3.SmoothDamp(rb.linearVelocity, targetVelocity, ref velocity .05f);
}
}
"""
I'm sorry i'm not know discord ^^'
A tool for sharing your source code with the world!
` ` `
not
` ` ` ` ` `
the ` is usually next to 1
A tool for sharing your source code with the world!
J'ai rรฉussi hourra
it is difficult for me to see immediately where I have to change and the consequences that this implies
the error list helps a lot. you should see what error you get (assuming you make one)
if I use LinearVelocity the consol tel me is not correct with the domain Rigidbody. I see my error
Oh, yes, the convention ^^'
why not let intellisense do the job
capital letters are important
Because i can understand, i'm beginner and i lost many time for this. I love do some videogame ๐
Yes, i learn this, i just forget..
if its only jittering in the game window then its probably the camera jittering, not the character
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
the camera controller also seems to be a separate script. try checking that (or send it here if you cant fix it)
Yes its separate from player
hey guys i followed advice from this video, but im a bit confused on how to implement ability cooldowns? how do i set a cooldown to an instance of a scriptable object, if thats even possible? https://youtu.be/0HCOZo5N-t4
Multiplayer Mastery Course - https://game.courses/mp/
Game Dev Course for Beginners - https://game.courses/bc/
Join the Group - https://unity3d.group/
Join this channel to get access to perks:
https://www.youtube.com/channel/UCX_b3NNQN5bzExm-22-NVVg/join
you may have the wrong scene open
you can search your project folder for scenes with:
t:scene
^ (same thing, but this also works)
Yes is the good option thank you, i try to reload all. i have all my Grid and tilemap thank you
Can't you just trigger a timer through a coroutine and block the execution of the ability if the cooldown is > 0 ?
thats what i tried doing but changing the cooldown for a scriptable object does it for all of them
since theyre meant to be readonly
@swift crag @rich ice all is right thank you โค๏ธ
so ive put all my player data inside of a different scripts, each aspect being a property, however its not showing up in the inspector, are properties not serializable?
wouldn't you just grab the cooldown value from the SO and use that for the timer?
yes but then how do i tell it which ability is on cooldown?
and then how does it tell the ability its off cooldown
nope, you need to use an attribute . . .
[field: SerializeField]
public int Health { get; set; }```
alr thanks
maybe scriptable objects are not the play here, ill experiment with some other methods
dont you have a script to manage active abilities?
Properties can't be serialized, but you can access the invisible backing field with an attribute by using the prefix field:. So, you'd use [field:SerializeField] to apply the SerializeField attribute to it. Note, that this is directly changing the backing field, not the actual property, so if you were to do something like put an event in the set accessor, that event would not be called
no, I'll look into that
so far the plan is for them to be one-shot abilities so I was hoping I wouldn't need that
a simple one could do, thats what I have. Also have the Instant cast mode vs "being placed " first.
what usage does { get; set; } have on its own?
i know you can put some extra functionality inside it but i have no idea what it does on its own
nothing it just says this property can be by default Set and Read
if you open the brackets then you can add items inside
get and set are like functions (called accessor actually)
Practically: It allows the property to be chosen as a target or source of a unity event.
You can't have a UI Input dynamically set a string variable, but you can for a string property
Wait, actually?
o, that actually sounds really useful
somehow i've never seen this before 
you mean the documentation or properties ?
properties, i cant imagine living without the documentation lmao
i've been programming for a while now but there's still tons of basic stuff i find that i've missed
So I'm having a issue where my shape cast is detecting I'm grounded before my like collision box itself is grounded
But moving it up prevents me from detecting slopped objects
My solution was instead of setting gravity while I'm on the floor to 0 I set it to -1 but I feel like this is a poor choice
Any advice? Heres the code
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
RaycastHit hit;
bool isGrounded = Physics.SphereCast(characterController.bounds.center, .18f, new Vector3(0, -1, 0), out hit, characterController.bounds.size.y/2, 3);
if (isGrounded && playerVelocity.y < 0)
{
playerVelocity.y = -1f;
}
Vector3 move = new(horizontal, 0, vertical);
playerVelocity.y += gravityValue * Time.deltaTime;
characterController.Move(((move * speed) + playerVelocity) * Time.deltaTime);
if (isGrounded && Input.GetKeyDown(KeyCode.Space)) {
playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
}
}
}```
When it was set to 0 I would just very SLOWLLYY fall the rest of the .4 y idk what unit unity uses roblox used studs lol
I think spherecast doesnt work if you're already casting from inside the ground iirc
its casting from my player
I think thats why I used overlaps
If you're using a character controller, it should already have an isGrounded bool you can use that works with slopes fine:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/CharacterController-isGrounded.html
isGrounded is trash
IT DOESN'T WORKKKK :(((
IT JUST RETURNS FALSEEEEE
it's fine if you move the controller only once per frame and include gravity in this movement
It works fine as long as you include some downward gravity in the one time per update you call it
You must actively move the controller into the ground for isGrounded to become true
Gliding along the ground doesn't count
Hi
does anyone know the version controll well, i have a problem where i got one version with one player, and my friend a verison with two players, when i watn to merge from his version it tellls me files need to be resolved or so, i do the conflict resolve and then i still cant merge without checking in again but then it beginns from the beginning again.
characterController.Move(((move * speed) + playerVelocity) * Time.deltaTime);```
tbh thats going backwards, I would figure out whats wrong with the spherecast. Also give overlap a try, never have issues with it
I did use overlap but someone said its bad and told me not too but I realize every programmer disagrees with every programmer so lmfao
I dont see how its "bad"
even the Unity Starter Assets controllers uses that method ๐คทโโ๏ธ
the only "bad" about it is, it doesnt give you the hitInfo like Casts do. So you need manually check slope angles with another ray
I mean I did fix the issue though with the gravity sorta by setting gravities default state to -1 while grounded
which honestly I feel like isn't the worse thing ever
I was just curious if there was a better solution
But your gravity is -9.81 normally?
yes
Just constantly try to accelerate the player downwards
well
You don't need to manually set the velocity to anything
Let me rephrase that
no cuz if I walk off the edge I go mak 12
Then you're doing gravity wrongly.
ah, I see the issue
I have to manually code in gravity so I have to apply it to the force
you're building up velocity forever in playerVelocity
yeah thats why I have the if statment
If you do want to keep track of that separately, then you need to clear it when grounded, yeah
You need to set the vertical speed to 0 if you're grounded, then apply one frame of gravity
I'm using a character controller so I have to apply my own gravity
yes thats exactly what the original Move. example code had
So if you're grounded your speed is basically constantly at "one frame of gravity" to move you into the ground
I get the slow falling issue doing that
If you're falling then you're not grounded
yeah but if I move the cast up I can't detect slopes
Again, don't use a cast at all
im willing to bet the issue is your Spherecast is already inside the ground when its trying to go (0,-1,0)
use isGrounded and properly apply gravity every frame
I did do that :( But sure I'll try it again lol
isGrounded is flimsy af especially fast on sloped surface
OH
WHEN I USE ISGROUNDED IT DOESN'T WORK
BUT WHEN SOMEONE ELSE TELLS ME TOO
IT WORKS
Then you did something wrong the first time
I copy and pasted my code from yesterday :(
I changed one thing
I move is grounded below the move code
when before it was above it
does that really matter?
Yes
Yes, because moving the character controller changes its state
the docs showed it being called before the move code :(
Is grounded returns true if the previous move call hits the ground
ok well thanks lol last time i'm trusting doc code
You should be calling Move exactly one time, in update, as the last thing you do
wait so grounded should be called before or after move
If you call it in more than one place, you're going to run in to issues
to be fair the idiots who put the example code made 2 Move calls
Grounded should be checked before the move, some downward force should be applied if it is grounded, and then move should be called. once
If you have .Move in more than one place, where you put the code determines whether it works or not
someone on this day was allergic to doing a simple + to make it 1 call ๐คทโโ๏ธ
so like this?
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 move = new(horizontal, 0, vertical);
playerVelocity.y += gravityValue * Time.deltaTime;
bool isGrounded = characterController.isGrounded;
if (isGrounded && playerVelocity.y < -1)
{
playerVelocity.y = -1f;
}
characterController.Move(((move * speed) + playerVelocity) * Time.deltaTime);
if (isGrounded && Input.GetKeyDown(KeyCode.Space)) {
playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
}
}```
nvm
docs had it being set to 0 if you are grounded but if its 0 then grounded doesn't work it seems
yes it should be 0
well when its 0 grounded doesn't find ground
Here's how it should go:
- Calculate your horizontal movement however necessary
- Check if you are grounded. If so, set your y velocity to 0. Otherwise, leave it u changed.
- Add your gravity value to the y velocity.
- Apply changes to your vertical velocity from jumping
- Move the character
when I set it to like idk -.5 it does
if (isGrounded && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
In that very specific order
did you also change the value the right of <
Oh I see the issue
I get it now
its because I did gravity calculation THEN set it to 0 so probably something something computers like decimals so I was technically like barely hovering over the ground?
or I'm shitzo and just the like deltatime of gravity fixed it
idk
It works now tho
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 move = new(horizontal, 0, vertical);
bool isGrounded = characterController.isGrounded;
if (isGrounded && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
playerVelocity.y += gravityValue * Time.deltaTime;
characterController.Move(((move * speed) + playerVelocity) * Time.deltaTime);
if (isGrounded && Input.GetKeyDown(KeyCode.Space)) {
playerVelocity.y += Mathf.Sqrt(jumpHeight * -2.0f * gravityValue);
}
}```
lines run top to bottom so order of operations matter
I should do the jump before move
oops
honestly for one day of unity i'm happy with this progress
Also, one thing you may want to tweak
the default minimum move distance is 0.001
I don't actually understand why you shouldn't just set that to zero
It often causes problems at high framerates
at 100 fps, that means you can't move below 0.1 meters per second!
I did see someone saying that and I already tweaked it
If I rotate the parent of the camera would the camera rotate with it?
Aka I'm asking cuz its not lol
float mouseX = Input.GetAxisRaw("Mouse X");
transform.Rotate(0, mouseX, 0);```
yes
no cuz I just wanted to get x working
its not rotating at all when my character is rotating
so You don't have any camera rotation scripts ?
nope
which script has this line
and which object its on
a new one and its on my capsule
hnn and camera is child of this?
using UnityEngine;
public class CameraScript : MonoBehaviour
{
public float xSensitivity = 150f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * xSensitivity;
transform.Rotate(0, mouseX, 0);
}
}
dont use * Time.deltaTime on mouse inputs btw
oh ok
mouse inputs already frame-rate independent
I'll fix it after my other issues
My only idea if that my movment isn't moving based on the local vector
wat you mean? why would movement affect rotation of child
if cam is child of capsule it should rotate with it unles you have a mouse look script preventing rotation on Y axis
I'm so confused hold on 
Ok I described that in the complete wrong way idk why I said this
My issue is that my character isn't moving based on the local vectors
But I think I can fix that
I don't know how I confused myself this badly
just ignore me lol
when you rotate ?
you aren't using the forward anywhere
yeah ik
.Move is relative to CC no ?
yeah I think so idk
Move works in world-space, so you'd need to use transform.forward to make the character move forwards, not Vector3.forward
ahh right. You also can use InverseTransformDirection iirc
ye I fixed it
I'm realizing unity wise I gotta do a lot more vector math than roblox made me lol
That goes from world-space to local-space
I just relooked at my roblox code to remember how to get to the local vectors
yeah to transform their moveInputs no ?
Vector3 move = new(horizontal, 0, vertical);
That would be backwards.
move is not a world-space direction right now
well, I mean
you can interpret it as one
inside .Move though
i forgot tbh
I just do the
move.y * forward + move.x + right
lol
someone once told me about the other method tho
yea
transform.forward is the world-space direction your transform is facing forwards in
These are equivalent:
transform.TransformDirection(Vector3.forward);
transform.forward;
I generally just construct a local-space move vector and then transform it into world-space
These are also equivalent:
transform.InverseTransformDirection(transform.forward);
Vector3.forward;
ah yes , so you can do cc.Move(transform.TransformDirection(move) * speed
Correct. That will give you world-space directions.
this gets rid of that sus
transform.forward + transform.right bs
Both are fine.
less clutter ๐
I prefer the former because it's a little more obvious what's happening, though
is there any concern about increasing rotation value beyond a certain limit? e.g. i have an animation that rotates the game object 720 degrees (barrel roll), if i keep doing that would it possibly hit a ceiling and crash?
or do i have to reset its rotation value at some point?
It's a float so the maximum value is 340282346638528859811704183484516925440. So you're probably safe.
is there anything inherently wrong with doing this? i originally wrote code in the update function but seeing as i want to do multiple unrelated things in update and want to keep it more organized, i want to put several functions in there
That's fine
thx
Not only not a problem but 1000% what you should be doing
for me it depends
if its only like 1-10 lines then i'll just use a comment
if its anything more then i'll typically do that
i didnt know that! i thought it would be creating garbage somehow (i dont know what constitutes that but it just feels dirty to call functions all the time)
You would need to call four billion extra functions in order to produce one second of slowdown
thank you very much. in all tutorials ive seen they just write the code straight into the update function, had no idea this was what you should be doing
placing your code in a method allows you to easily modify that code and reuse it, if necessary
imagine if a script did multiple things in Update (which is normal) and everything was placed inside. it'd be a long mess of code with you having to figure out where one part ends and the other begins . . .
some of them do this because the code is small and doesn't constitute needing a methodโas it's only for tutorial purposes, but it is convenient to place it in a method . . .
that makes sense, thank you
thats generally good practice is to break as much code up into small methods and subroutines, readability is usually more important than anything
damn, now i feel like i need to start breaking my code up into more methods 
if it involves a .cs file then it probably goes in this channel
probably #๐ปโunity-talk
i see thank you
how do i fix?
The namespace Photon.VR does not have a class/namespace called Saving
would you by any chance know if theres a chat for unity - linux? thanks
nope
#๐ปโunity-talk is pretty universal, the specific channels are for more common issues (or so i assume, idk i didn't make the server
)
im a member of 3 Unity discord servers.. none of which have dedicated Linux channels
idk how i screwed this up lol isnt a vector3 just 3 floats?
yes. but theres specific ways to do that
oh wait i think just putting "new Vector3" fixed it
new Vector3(floatX, floatY, floatZ);
You declared a tuple by doing (x,y,z)
thank you!
hm, this isn't working anything like i thought it would. is there a better way to do this? trying to have a barrel roll/evasion animation move the player child object (the sphere is at the same level in the heirarchy and is just there to show where the parent object position is (the center is offset from teh actual parent but just for visibility))
thats the event triggering at the end of the animation
also its only working sometimes, randomly the parent position doesn't update
So for GitHub do changes suggested on the site adjust the code on my machine directly? Noob question just want to make sure I don't accidentally obliterate my files.
pretty sure changes only get made on your device if you git pull
if you make commits via the github site then yes, when you pull those changes they will be reflected within your local files
you will also be required to pull changes if any exist on the remote before you can push any
is it fine to have something moving in one direction basically indefinitely? an instance probably wont move for enough time that it matters probably, right? currently i have the x position of a gameobject gradually going down
after like 10 seconds it goes from ~2 to ~(-10)
(this is meant to be a loading screen of sorts though so it wont be up for very long anyway)
issues only arise once objects get to about 10k units from the origin
again, you have to pull changes before you can push new ones
if its only going to be in the scene for that brief time before its destroyed it doesnt matter. i'd get in the practice of making sure not to leave any loose threads as a habit but for that case it sounds fine
Is using animations for movement too janky or bad practice? As a rule of thumb?
If your player or object is going to be solely root motion or an active ragdoll of sorts, then no it shouldn't be janky. I definitely would not mix animation based movement with normal scripted movement though.
In this case Iโm trying to make a barrel roll evasion kind of ability (see above video)
Trying to fix the position post animation has some janky results and I canโt figure out what it is
I would not mix animation based movement with scripted movement, why not just make it solely scripted movement for something that simple?
Animation seemed like it might be easier to make look smooth. But yeah guess not
how do i fix my camera being on the left?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
public GameObject player;
private Vector3 offset = new Vector3(-8, 5, -7);
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{ //offset the camera behind the player by adding to the player's position
transform.position = player.transform.position + offset;
}
}
- !code
- what direction do you think offsetting the position by -8 units on the X axis will be?
- obligatory: use cinemachine
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
Change the -8 to 0
You can experiment with stuff like this in the game view, select the camera from the scene browser and adjust it to where you want it while in game mode then reflect that in your script
show the car object and how you are moving it
the code?
yes, and the inspector for the car
probably because it has no collider
the car?
yes
Hey all, I have the position and rotation of VR controllers that i want to display as an object within unity, the thing is. I want these controllers ingame to have collision, but trying to update their position with MovePosition() and MoveRotation() looks very jittery when updating at the freqency of the physics system, rather than at 120FPS, even with my rigidbody set to interpolate. Is there anyway i can get my controllers position to update based on framerate, while still maintaining physics?
if its still bad even when using MovePosition then increase the physics step rate? MovePos/Rot should be using interpolation already ๐ค
Isn't that going to cause much worse performance overall though?
It may but all i can think of is either the physics steps are too few or maybe you are changing the position too quickly? if you make it say twice as often does it look better?
if i put it in update instead
private void Update()
{
position = actions["Position"].ReadValue<Vector3>();
rotation = actions["Rotation"].ReadValue<Quaternion>();
rb.MovePosition(transform.parent.TransformPoint(position));
}```
Movements when im stationary are very smooth, but whenever i move the parent it is attached to, it starts to jitter
i feel like im approaching this in a bad way
but not sure how else to
they are kinematic right?
Should they be? I thought that would mean that they no longer collide with stuff
I wonder though due to the interpolation being to the old world pos, as you move the character it is now going to be incorrect ๐ค
im not fully sure how it interpolates
yeah, i dont see a function for rigidbodies to do it relatively though
ill try with kinematic one sec
you can make it teleport too with .position
but wouldn't that mean it could potentially phase through a wall?
they would yea, do you have the controllers as children of the player that moves?
i do yes
this is what my hierarchy looks like
but whenever i move the parent it is attached to, it starts to jitter
Yes, moving a rigidbody's parent transform will mess with the physics and interpolation
Just like you would move the rigidbody's transform directly
i see, how should i approach it then?
fyi i am moving the parent with AddForce, not .position
Alright, well I don't have good experiences with parenting rigidbodies to each other
Try having them as "siblings" instead?
And make the hands follow the player manually with forces or something
So i just reference the player in my hands script and work out the position relative to that?
Yeah
alright i'll give it a go, thanks
You could also use some type of Joint but I think you get better control here if you do it manually
still jittery unfortunately
tried with both Update and FixedUpdate
What is your setup currently? The hands don't have a moving parent now, right?
You can show your code and I can take a look if I see anything problematic
nope, its top level of the heirarchy
public class ControllerTracking : MonoBehaviour
{
public enum Hand
{
Left,
Right
}
[SerializeField] private Hand hand;
[SerializeField] private Transform offset;
private Rigidbody rb;
private Dictionary<string, InputAction> actions;
private Vector3 position;
private Quaternion rotation;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
private void Start()
{
actions = InputManager.Instance.GetActionMapFromDefault((hand == Hand.Left ? "Left" : "Right") + " Tracking");
}
private void FixedUpdate()
{
position = actions["Position"].ReadValue<Vector3>();
rotation = actions["Rotation"].ReadValue<Quaternion>();
rb.MovePosition(offset.TransformPoint(position));
}
}```
Also make sure that it's not actually the camera jittering
camera was fine before so i dont think thats it
I don't really know how well MovePosition works with non-kinematic bodies, I really only use it with kinematic ones.
Even the docs say
Moves the kinematic Rigidbody towards position.
yeah, im just completely stuck with how else to implement it though, if i use .position its gonna phase through objects
Calculate velocity from the difference
Do you have any other code affecting the object, such as rotation code?
the hand itself, no. But the player can both move and rotate
How does it rotate
var diff = targetPosition - rb.position;
var vel = Vector3.ClampMagnitude(diff, limit) * speedMult;
rb.velocity = vel;```
This would make it move towards the target position by velocity rather smoothly
using .AddTorque()
Isn't this going to cause a bit of a timelag between my controller IRL and hand ingame though? While it may look smooth, if there's a disconnect between real life and game that's going to be very annoying and immersion breaking
i'll give it a go, but i'm guessing that'll be the case
It can be made snappier, but if you want it to be absolutely responsive then I'd probably separate the hand's visuals from the physics. Update the visuals to the target position while the rb is catching up
You can also use kinematic hands and MovePosition() but then I think you'd need to implement collision checks with something like SphereCast
if i stuck my hand through a wall though, wouldn't the visual still go through, while the invisible collider is where it should be?
You could snap the visual to the physical hand when colliding, but yeah that would probably look bad now that i think about it
Yeah it seems like quite a hacked solution
I'm not a VR dev but I'm sure this problem has been solved, have you looked online for resources on VR hand collisions?
Yeah, i've found it really annoying to be honest. Unity provides a default XR toolkit with some built in stuff, but a lot of that is very generic with basic movement for example which don't really work for my project. That and all the tutorials on youtube i seem to find are outdated even a couple months after release, and a lot of the scripts used seem to get frequently deprecated and replaced. That's why i figured id just do it myself, and make picking up objects and such by myself, but i keep seeming to get stuck at simple hurdles like this where it feels like the solution should be easy, but it ends up being a lot more convoluted.
and the demo scene they provide doesn't have physics collisions on hands, so i cant really see how you would go about doing it now either
In the end i've tried this. And it's actually pretty snappy, thanks
not that noticeable
Does anyone know if it's possible to make a local multiplayer in unity 3d with split screen with a rigidbody instead od character controller?
with the new input system
i saw every tutorial using that
of course it's possible
so i can just follow the same tutorial but using rb?
i mean, moving a rigidbody is going to be different than moving a character controller, but not by much
Anyone have any idea how to make an edge detection for 3rd person? tried couple methods like shooting 2 raycasts and try to compare their normals but i don't think that worked well
Wdym by "edge detection for 3rd person"? You'd usually say "edge detection" in the context of shaders, not 3rd person.
wouldnt u compare distance? like if 1 hit at zero and 1 hit (1 meter down)
Ah, like ground edge?
thats what im assuming.
ye
so that you can stop the player from walking off the edge?
nah so the player can jump between them
yes this.. and not sure (2) raycast is adequate
but it could be..
can't the player just...jump?
or will this be a little animation
where the player isn't directly controlling the movement
Is it like to make them jump automatically?
Couldn't you jump even if there's no edge nearby in prince of Persia?
ya, i believe u could.
Oh nah it's like high building that you can teleport to it's edge
tried to use overlapsphere too but didn't work either idk
If there are predefined places where you can do that, maybe just place some empty gameObjects that you can use as points to teleport to.
well i thought of that, but for long term i'll get kinda lazy xD
So making it by script should be easier anyways
You could raycast down from the player to see if heโs on a platform.
You could also raycast down from a point X distance in front of the player and see if it hits the same platform at the same altitude.If the altitude is more than a certain amount lower (or you hit nothing) then it might be a ledge.
Of course it also might be you are standing at the base of a mountain, and when you raycast from within the mountain you wonโt find the mountain.
Therefore you might want to also raycast forward to see if you are hitting the base of a cliff that towers upwards in front of you.
Writing computer code to figure out your environment can be tricky, but it certainly is possible if you break it down into logical raycasts as you โFeel outโ your world around the character.
https://discussions.unity.com/t/2d-platformer-need-advice-on-how-to-detect-if-player-near-edge-of-platform/839792
You could still make it by script. An editor script.
Honestly, I think we're missing some context here.
If all you want is to find if your player is near an edge and want it dynamically, just get the all of the vertices on the object you are currently standing on and calculate the edge normals for all of the vertices, then just find the closest edge that is near the player. Unless I am missing something that should work and as an added benefit it does not rely on the direction the player is currently facing.
Of course you may need an offset to back your character up a bit so you don't fall off of the edge
Ok sorry for the missing context, it's about teleporting to the edge of a building from down or far from it, i used raycast to try and get the edge with it but didn't quite get it that's it
Well, maybe share the code that you have now.
Like this?
Would it be possible to make a compilation game similar to Megaman Legacy Collection in unity?
private void Update()
{
Vector3 onerayOffset = mainCamera.transform.position * camHeightOffset;
Ray ray = new Ray(onerayOffset, mainCamera.transform.forward);
if (Physics.Raycast(ray, out firstHit, raycastDistance, buildingLayer))
{
Vector3 secondRayStart = firstHit.point * rayOffset;
Ray secondRay = new Ray(secondRayStart, mainCamera.transform.forward);
if (Physics.Raycast(secondRay, out secondHit, raycastDistance, buildingLayer))
{
Vector3 firstNormal = firstHit.normal;
Vector3 secondNormal = secondHit.normal;
float normalDot = Vector3.Dot(firstNormal, secondNormal);
if (normalDot < normalDifference)
{
detectedPoint = secondHit.point + Vector3.up * camHeightOffset;
}
}
}
}
yup
Why not? Why would making multiple games in one be at all a limitation of the engine?
Because I don't know how to put roms in a unity game.
I also don't know how to do button mapping for the roms.
One issue that I can see is that you're multiplying a position vector to offset it for secondRayStart. That's not gonna work.
You'll need to calculate the offset from the original ray direction and the hit normal
Or, maybe no need for a hit normal.
ah the if that is the case then just do this #๐ปโcode-beginner message but instead of the object you are currently standing on, shoot a raycast from camera to the camera's forward direction then use that object for the calculations and find the closest edge to the hit.point of the raycast. It'll look something like this
Blue is the distance between normal's
Orange is the normal's
Magenta is the closest distance
That's how I would probably do this
Just making sure I pinged you.
what do ROMs have anything to do with that? you can just make different games within the same project
It's a game compilation similar to megaman legacy collection.
so you want to use existing games? because you won't be doing emulation in unity
You want to make your own games? Or existing?
It's a collection of games.
It's a collection of games.
repeating the same useless phrase isn't really all that informative
It's like this: https://youtu.be/QNTZnjzFH8o?si=CDPQHv1PY-FMvz15
Gonna take you for a ride back to the arcades with MARVEL vs. CAPCOM Fighting Collection: Arcade Classics! 7 legendary games, all in one Super Heroic collection, available NOW on Nintendo Switch, PlayStation 4 and Steam! Xbox One version is also coming in 2025.
- X-MEN CHILDREN OF THE ATOM
- MARVEL SUPER HEROES
- X-MEN VS. STREET FIGHTER
- ...
oh and if you would want to get rid of the bottom normals from the list, just do a dot product to find only the top normals
can you actually answer the question that was asked instead of providing redundant information?
Roms are files that can be run by emulators. Unity has nothing to do with roms. You can't put roms in unity.
It's like an emulator only you can play a certain amount of games.
If you just want to include several games that you developed in unity into one application, that's certainly possible.
yes i'm aware of what you are referring to. you have not yet actually provided the answer to the question that was asked. are you trying to use existing games or are you just trying to make a game with a bunch of different new games in it?
I'm using existing games.
are they your games
Do you have the rights to publish these games and are they built for the platform you want to run them on? Or are these actually rom files as you mentioned earlier?
No. I'm going to pitch it to the companies.
lol good luck with that
I still don't know how to put a rom in unity.
In technical context, you can certainly do it.
Not rom.
you don't because roms are for emulation.
Unless you port/develop an emulator that runs in unity.
So I should just remake the game from the ground up?
Here's a simple question: what platforms are these games made for?
Mostly Arcade.
Then yes. You'll need to remake or port them.
How do I port them?
It's like you can't put a CD into a USB port and hope that it works, can you?
You'll need to have access to the source code/the original project and build it for the desired platform(additional project/code modifications might be required). If you want to specifically use unity, you'll probably need to rewrite the project in C# and recreate the assets/levels in unity as well.
I can do the recreation thing.
And rewrite the code in C#.
How performance wise is this method?
And most importantly, you'll need the original developer/publisher permission to do so.
depends on how many vertices the Model has, but it shouldn't be that bad as you wouldn't be doing this for multiple objects, you would only do this for 1
I used a slightly tweaked method to make AI pathfind to a hiding spot dynamically and the performance seemed fine (keep in mind it was in 2D but I would guess it would be roughly the same in 3D)
I think it would be easier to adjust a bit your own method and it should work.
Disregarding performance. Just effort wise
Is this an ok way to change sorting layer of my 2d sword when switching to the left or right?
private void MouseFollowWithOffset() {
Vector3 mousePos = Input.mousePosition;
Vector3 playerScreenPoint = Camera.main.WorldToScreenPoint(playerCore.transform.position);
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
if (mousePos.x < playerScreenPoint.x){
activeWeapon.transform.rotation = Quaternion.Euler(0, -180, angle);
sprite.sortingOrder = 4;
} else {
activeWeapon.transform.rotation = Quaternion.Euler(0, 0, angle);
sprite.sortingOrder = 3;
}
}
What alternatives are there to tilemaps? SetTilesBlock is just not fast enough for me. My use case doesn't require colliders or that sort of stuff, only a grid and ways to click and change tiles (in runtime). I've seen an asset to make shader based tilemaps that span thousands of tiles with no performance drop but I can't afford that. My chunk system is not enough to reduce the amount of tile changes. I've also heard about coroutines. My use case has a single plain layer so I'm not sure how would I do that. Any help is appreciated.
I have more or less the exact same problem as you. At some point I looked into rendering each tile in batch like this.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Graphics.RenderMeshInstanced.html
I only render the tiles within the camera view
Wait what is that? Does it have anything to do with tiles?
The overall process is you render multiple quad meshes, each with the material that you want
one quad = one tile
Oh so I don't display anything from the tilemap and use quads instead
Yep
Is zooming out too much an issue for that?
I'm having a rough time trying to understand pulling a variable from another gameobject.
Essentially, I have a "weapon controller" which holds on to the attributes of a weapon and an object that follows my mouse and instantiates a bullet on click. What I'm trying to do is give that bullet a damage value when it instantiates.
Thoughts I've tried
- Instantiate as a child and get parent damage value. (Not instantiating as a child, instantiates at the bottom of the whole scenes hierarchy. Can't seem to figure out getting it to instantiate as a child. Is this because of the "parent transform" situation? Transform itself being part of parenting is incredibly foreignt to me, I read the doc a few times and still don't feel like I understand whats going on there.)
- Call to the weapon controller object and get the damage value. Can't seem to get the instantiated bullet to find the weapon controller on spawn. Gotta be missing something here.
- I also read that you can't pass a method when you instantiate?
I'm suuuuper new and coming from godot, so I'm still in the process of learning. I know I want to have a lot of these items separate so they can be modular in the end. If someone can point me in the direction of what I need to be looking at, I'll gladly dig through the documentation to try and help understand.
whatever instantiates the bullet can have a reference to the weapon controller (if it isn't the weapon controller itself) and just pass the relevant data to the bullet when it is instantiated.
https://unity.huh.how/references/simple-dependency-injection
I must be missing something. Going to do more digging but I'm getting the error "type' does not contain a definition for 'name' and no accessible extension method 'name' accepting a first argument of type 'type' could be found (are you missing a using directive or an assembly reference?)." error when writing out the code on that site. Compiler error site says it occurs when you try to call a mehtod or access a class member that doesn't exist. Which I'm assuming is because the bullet doesn't exist yet?
Thank you though! Nothing a few videos won't teach me XD
Which I'm assuming is because the bullet doesn't exist yet?
no, it means you are trying to use a property that does not exist in the code.
also share your actual error instead of an approximation
Alright, having some issues with a part of my code. Currently, I'm trying to delete all the children of an object, but whenever I call for it to delete, it won't "delete" them? (It's weird. It doesn't show the children under the object, but it still counts them in my code.) Any ideas of how to fix this?
public void ResetPlayerHand()
{
for (int i = hand.transform.childCount - 1; i > 0; i--)
{
Destroy(hand.transform.GetChild(i).gameObject);
}
handManager.cardsInHand.Clear();
Debug.Log("Cleared cardsInHandPlayer");
hand.GetComponent<CardValuesScript>().handValue = 0;
Debug.Log("Number of children in handtransform " + hand.transform.childCount);
}
}```
Destroy queues the objects up for destruction at the end of the frame, they aren't destroyed immediately
"Actual error"
CS1061 'GameObject' does not contain a definition for 'Initialize' and no accessible extension method 'Initialize' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
This error is given when I hover over the "Initialize" section of my code (and in the error list)
I can grab the code, but it's from 2 different scripts
you need to use the actual type of component you care about for your prefab variable instead of just GameObject
or you need to call GetComponent on the gameobject after it has been instantiated
okay, maybe I should post the code....
var instance = Instantiate(bullet, bulletTransform.position, Quaternion.identity); instance.Initialize(damage);
yes now re-read both of my messages because they are two options for fixing your issue
Does anyone have an idea why changing scenes doesn't work in unity 6000.0.32f1 compared to code in unity 2022.3.50f1? I just switched my project over from the latter, and the script is broken. the code is public void start() { ClosePhidgets(); SceneManager.LoadScene("Scene1"); SceneManager.SetActiveScene(SceneManager.GetSceneByName("Scene1")); }
define "doesn't work"
well naturally an error would prevent the code from running, so maybe share the error
NullReferenceException: Object reference not set to an instance of an object
ButtonScript.ClosePhidgets () (at Assets/Scripts/ButtonScript.cs:64)
ButtonScript.start () (at Assets/Scripts/ButtonScript.cs:20)
UnityEngine.Events.InvokableCall.Invoke () (at <44f3679c53d1477a9c6e72f269e3a3a9>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <44f3679c53d1477a9c6e72f269e3a3a9>:0)
UnityEngine.UI.Button.Press () (at ./Library/PackageCache/com.unity.ugui/Runtime/UGUI/UI/Core/Button.cs:70)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at ./Library/PackageCache/com.unity.ugui/Runtime/UGUI/UI/Core/Button.cs:114)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at ./Library/PackageCache/com.unity.ugui/Runtime/UGUI/EventSystem/ExecuteEvents.cs:57)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at ./Library/PackageCache/com.unity.ugui/Runtime/UGUI/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at ./Library/PackageCache/com.unity.ugui/Runtime/UGUI/EventSystem/EventSystem.cs:530)
can you please explain the error for me? I dont understand it
if only there were a convenient link that provided a brief explanation of the error as well as extensive troubleshooting steps for resolving it
sorry, the page was mostly empty, so I automatically assumed it was taken down.
Right. GetComponent would cause errors unless it's serialized according to the site you sent.
When I read through the serialization section, the first 5 steps are present in the DI page and I'm not seeing the difference. I may be missing a reference somewhere. It also mentions that cloning a component with instantiate has all attached objects and components with it. In this case, the script which has the Initialize function. Which is set to public as well. Maybe this is where I'm not understanding something?
you're trying to call the Initialize method on a GameObject variable when that is not where you've declared that Initialize method. you need to refer to that component to call Initialize
(I understand you are working with two people at once, no pressure) After reading the site, I still do not understand my problem. I am trying to change scenes and, to the extent of my knowledge, there are no variables
in the example code the _prefab variable is not a GameObject variable, it is the component that the Initialize method was declared in
your error occurs before the line of the scene change.
so therefore the scene change doesn't happen. you need to resolve the error first, before worrying about the scene change
figure out what is null on line 64 of ButtonScript.cs
Just in case it's not clear: runtime errors prevent further code in the method from executing.
Thank you for helping, it is working now
I don't think I understand. Don't unity tilemaps already use quads to render the tiles? What's the advantage of doing this? Where can I find the specifics?
Another question involving scenes (not that related though). I am publishing a game through WebGL, and the scenes are in the wrong order. How can I control the first scene?
rearrange the scene list for that platform's build profile
https://docs.unity3d.com/6000.0/Documentation/Manual/build-profile-scene-list.html
I did that, yet nothing changes
unityAction cannot exist in interface right?
hi. i'm having this bug where randomly after falling or moving sideways, my character can't jump.
https://scriptbin.xyz/owepagihis.cpp this is everything jump related I have in my movement script
i've tried debugging (see fixedupdate) and the conditions required to be able to jump are met. still doesn't
Use Scriptbin to share your code with others quickly and easily.
Depends on what you mean by "exist".
You should debug in more appropriate places. For example, log canJump in your jump method.
the issue is it's not letting me jump after reaching grounded state, logging while the character is in the air is not what i'm looking for
where are you even calling Jump
right i always forget to add something
{
horizontal = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump"))
{
Jump();
}
}```
you call Jump once per "Jump" button press, however you only update the grounded state in FixedUpdate so your object may appear grounded visually, but if you press that Jump button between when it appears grounded and when you actually update the grounded state then it just won't jump
i am checking the isGrounded parameter, made it public so i could see it reflected
also consider logging the relevant values when you get your Jump button input
don't rely on watching the inspector, log the info at the time you actually use it instead
Hey, I have a click sound object with a click sound but it's in dontdestroy on load and not in this scene. is there any simple and efficient way to play it that's not just finding it and playing it within the script?
-# โ
Solution I went with: GameObject.Find("ClickSound").GetComponent<AudioSource>().Play();
if it doesn't exist in the scene you can't just drag it in, so you'll need some other way to get a reference to it
moved the debugs to the jump function, added isGrounded and labeled them for clarity. this screenshot is from me spamming jump and not being able to
all the conditions are met
it's really weird
then there is something you've left out that is affecting it
Do what I mentioned.
yeah i'm just going to do a find and play it trhough the code
canJump being disabled when it shouldn't be is the reason I can't jump, I can log it if you insist but it's going to be false when it shouldn't be
then you need to find out why it is not being set to the value you expect
Great. That's already progress. Now you just need to know when and why it's being set to gals/true.
i don't really have an answer for that, canJump relies on three variables, those being logged above
the conditions are met
Do they? Debug all the conditions present in the JumpCheck method.
double check the conditions. because the most recent screenshot you've shown would indicate that canJump has not been assigned the value of true that frame
It seems my project is not being sent to unityPlay no mater what, can anyone please help?
canJump relies on linearVelocityY, isGrounded, and jumpAmountRemaining
yes that is clear. read your code and the screenshot you sent to find out why
those are the three variables being debugged in the screenshot above
It relies on the if and the else if to be false.
Are they being false when you're supposed to jump?
why even have this canJump bool anyway, it seems superfluous when you could just check if you have jumps remaining
okay hold up i'm getting dizzy
just wondering how i can make my camera shoot a raycast and detect wether it hits an object or not
no they're not, remaining jumps are 1 when i'm supposed to able to jump
if (isGrounded && rb.linearVelocityY < 0.001f)
{
jumpAmountRemaining = jumpAmount;
}
else if (jumpAmountRemaining <= 0)
{
canJump = false;
}
else
{
canJump = true;
}
with this information, what has canJump been assigned to this frame?
does anyone know how to fix this bug?
Right. Then can jump would not be set to true.
Programming basics: only one of the if/else if/else blocks can be executed at the same time.
The order of the scenes is defined in the build settings.
oh
right
well that was pretty silly wasn't it
and now, this is the part where you realize the canJump variable is useless. just check if you have jumps remaining in your Jump method instead
I switched the build settings, and even added random text to my scene. nothing is working
Sounds like either the build is failing or you're testing an older version of the build.
how can I see if the build is failing
when you build it look at the console
what do you mean by that?
i mean, when you build the project for web look at the console in the unity editor. if the build fails it will tell you there
It does not
so how is it an older version? I go to the opened page, press update, then press play
you did build the project again, right?
Are you doing build & run or something else?
in this window, I am pressing publish
when was the last time you actually built it, because it seems like it was not within (at least) the last 57 minutes