#💻┃code-beginner
1 messages · Page 498 of 1
its not once you learn all the basic pieces
your only limit after that is how much your brain can muster some logic 😛
yeah its just so hard when you have no understanding, im starting to pick up on certain things
like i understand the logic of it, i just dont know how to write it out
so i should add something like the line you made after the first block is placed?
If you can already understand the logic then you have a good headstart
The syntax etc. comes with practice
yeah thats the problem im having
How long have you been learning?
gridCube.transform.position = new Vector3((bottomLeft.x + (blockSize/2f)), (bottomLeft.y - (blockSize/2f)), gridCube.transform.position.z);```
why with this line of code the blcoks get placed here? (blocksize = 24f)
3 days 💀 but like 12+ hours each day
ah i forgot, jumping with addforce is fine Unless you have i said it the complete oppositeForcemode.impulse at the end of it
Yeah no one knows what they are doing after 3 days
again you're using world position
I think
wait
So its completely fine if its in Update?
oh so i need to add impulse to it?
Impulse for one-shot forces
Impulse is fine in Update / One frame function if its in Impulse
// Bottom left corner
Vector3 bottomLeft = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, 0));
// Place block
gridCube.transform.position = new Vector3((bottomLeft.x + (blockSize/2f)), (bottomLeft.y - (blockSize/2f)), gridCube.transform.position.z);```
this is the full code
where do i put it
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(new Vector2(rb.velocity.x, jumpForce));
}
}
second parameter of AddForce look it up
okay so after jumpForce)?
oh ok so which one is the square the white one ?
oh ignore that
yes you need 2d version
This is how I usually reach the documentation
like this?
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(new Vector2(rb.velocity.x, jumpForce)ForceMode.impulse);
}
}
you need a ,
no
oh thank you for reminding me
ForceMode is wrong
the square i am placing is the black one
you need to configure your IDE
you need ForceMode2D
impulse is also capitalized which leads me to believe OP does not have configured IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
what is IDE
do you have a loop or is that the only code ?
integrated development environment (IDE)
the thing you write code in (ideally)
is that the thing when you connect your unity to visual studio?
yes
I have that set up
visual studio is an IDE
visual studio is the IDE
i have a loop, let me send it all
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
GameObject gridCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
Renderer renderer = gridCube.GetComponent<Renderer>();
if (height % 2 == 0)
{
renderer.material.color = Color.black;
}
// Bottom left corner
Vector3 bottomLeft = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, 0));
// Place block
gridCube.transform.position = new Vector3((bottomLeft.x + (blockSize/2f)), (bottomLeft.y - (blockSize/2f)), gridCube.transform.position.z);
}
}```
widh and height are both 10
oh
well not according to line of code you sent
it would give you an underline red
weird but also , you're not using i or j in the placement too
maybe try can you try Camera.main.ScreenToWorldPoint instead of
Camera.main.ViewportToWorldPoint I think ?
this has no errors so there are no red squigglys
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(new Vector2(rb.velocity.x, jumpForce), ForceMode2D.Impulse);
}
}
}
atm i am not, first i want to be sure that the block is placed on the right place
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
well now its wirtten correct thats why, try writing it with non-capital i
configure it, right now its like using notepad
without the + pixels it works
yeah
so blocksize/2 is probably wrong
yes i have it setup already
i also think that
you see red underlines when with a lowercase i?
yes i have been able to see that
but why? as far as i understand +24f (exmaple) should add 24 pixels
okay good
I edited this in discord not visual studio
sorry for the confusion
well now you can use the addforce in update()
try rq
gridCube.transform.position = new Vector3(
bottomLeft.x + (i * blockSize) + (blockSize / 2f),
bottomLeft.y + (j * blockSize) + (blockSize / 2f),
gridCube.transform.position.z
);```
i have another question, when i jump midair and walk in to a wall (while still being airborne), why do i stick to the wall instead of keep falling @steep rose
ah shit lol myb I think you want
bottomLeft.x + (i * blockSize),
bottomLeft.y + (j * blockSize),
gridCube.transform.position.z
);```
because physics
but why do i not fall down?
is there anyway to make my character fall?
when something hit the wal it stops velocity forward then falls down
now it stats from the bottom left, but still it isnt added the half pixel size
i will try writing a code for this
on step at a time ig. lol what is blocksize set to
you can use a physics material set to NoFriction on the collider, that might solve it
im guessing ill need to use tags and like a wall check or something?
24f
meters?....
but then the floor will be slippery correct?
should it be pixels?...
yes unity unit is 1m
Btw, manually writing rigidbody movement is not an easy task so don't be discouraged because you will run into quite a few issues
thats why Pixel Per Unit exists
you would want a https://docs.unity3d.com/Manual/class-PhysicsMaterial2D.html
it could be yes. if you use addforce that is that accounts fr friction
what I typically do is use a SweepTest or raycast
if the path is blocked dont apply force that way
you either would make a different collider for wall collisions or write your own friction code
what do you use for this?
is it just a ground check but for a wall?
I dont like messing with Physics material to solve it as i found it to cause other issues. SO I do the thing I just said lol use casts
pretty much
Raycast in the direction of movement, if something's in the way, don't move
and make it only when you are airborne as well
what is that?
to determine how per meter how big ur image is
eg
32 pixel square, set to 32 PPU
32 pixels = 1 unit = 1m in unity
for my scipt to detect im airborne do i do something like rb.velocity.y > 0
you would do !isgrounded, as long as you have a grounded function of course
It is how many pixels are in a unit
dont you have a isGrounded?
and how much should i make that?
understand thx
to make isGrounded dont i need to make a variable?
a boolean yes
How many pixels do you want to take up 1 unit?
isGrounded = GroundCheckMethod()
idk, 1 pixel = 1 unit?
but you would need to activate it/deactivate it by raycast/ spherecast /checksphere etc
so private bool isGrounded
but your box is not 1 pixel big lol
how much is my box?
oh the black box
you have to check the sprite texture settings
hold on I will be right back I am going to try to make a code
Sure, try that if you want
i was thinking the main camera
and see what it does
how can i do that if the box get created by the code?
if you're using the default unity square idk what the PPU is and i dont know how to change is as the texture is hidden for some reason
okkk, thx
thats tricky idk tbh lol
[SerializedField] private bool IsGrounded;
Isgrounded = raycasthit;
// you could also do checksphere as well
nice ahah
dms
IsGrounded = raycastHit 😛
if else is redudant for bools result
This is Mega Man. He is 21 pixels across. If you wanted Mega Man to be the same size as a cube of scale 1,1,1, you'd make his sprite's PPU 21.
my brain is not working today 😂
water for me
my water is just hot 😛
the problem is that i cant access megaman (in this case) because megaman will be created by the script
It's work! Thank you very much!
But jumping works crookedly... He jumped once and that's it, and he jumps very badly
Here code: https://hastebin.com/share/iyafazuwey.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
with spices lol
what is SerializedFeild and what is raycasthit
what how did i do that 😂
You could keep your old rb.velocity.y when you change the velocity
Any method by which you create a Sprite, be it importing or generating, will have the ability to set the pixels per unit
discord added automatically adding link tags
if you paste link into text it auto creates the required markdown
neato
[ThisIsALink](https://)
i was wondering how you did that
how? i cant access the inspector
i read this but what does serialize mean
just means to organize everything neatly where it can be easily read
it just gives the public effects to the private void?
I never said to use the inspector, I just said to change the pixels per unit. However you are creating it will have an option for that
In this case, it mostly means you can modify it in the inspector, despite being private
no it only allows it to be able to be seen in the inspector
so it doesnt actually do anything?
Hello, someone know how to declare a list in list ?
in unity yes it exposes them (private stuff) in the inspector or public ones also show up
List<List<SomeType>>
i dont know how to do it, do you know how?
Public makes it public to all other scripts
I don't know how you are creating it
to be used
OHHHHH so it makes it public for the inspector tab but no other scripts or gameobects, correct?
technically yes its not public though
its still private, its just "exposed" in the inspector
aka being able to be modified in inspector as if it was done in the code
GameObject gridCube = GameObject.CreatePrimitive(PrimitiveType.Cube);```
Basically. It has other affects on things like writing an object to disk, but for the most part, you can consider it as that in Unity
This isn't a sprite, this is a Mesh
so whats the point of it? why woudl i keep it private instead of making it public at that point
encapsulation
so it doesnt mess with other scripts
very important concepts of OOP
oh okay makes sense
So you don't change it in other scripts, forget about it, then come back to your project a month later wondering why the hell you keep ending up grounded while 20 feet in the air
so other scripts dont accidentally reference it and modify it
oh ok, (so? sorry i am a beginner ahah)
Pixels Per Unit is a property of sprites. Meshes don't have PPU because they don't have pixels
they just are that size
literally learning more in a 20 minute conversation in discord than 10+ hours on youtube
You just need to make your blockSize smaller in code
i guess just being able to ask questions is that powerful
Thank you, I tried it before but idk why it works now
well yes, its good to ask questions for things you do not know
oh ok, easier that i was thinking
this applies to everything
with proper research and base knowledge eventually you wont ever need youtube vids at all
yeah i try not to use youtube, its literally so terrible for learning tbh
just make sure to
anything you do not know etc. and yes doesn't hurt to ask clarification here
the problem is that i want to be sure that the block gets placed in the bottom left corner but not from the center
it is at bottom left corner tho
looks like it
it is
they just basically give you their code and dont explain anything, and even when they do explain it, they dont explain why stuff is happening or how its happening
but from the center of the black block
well yeah thats where the pivot is
thats why we exist
we explain (hopefully)
transform.position always goes from the pivot
can i change it?
https://hastebin.com/share/qewukizuve.csharp
What do you think? Is the code correct?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
its tricky in unity, you either make a parent then adjust child until it looks correct as pivot you want (then use parent transform.pos)
or you use modeling program to fix it beforehand
or just add offset in code to compensate
if it was a sprite i would just add half of the pixel size, and i guess i cant make sprites with code right?
you would add from the middle the halfs yes
what?
if block is 6,6 and pivot is 3,3 you add the 3,3 offset
the block is 1,1. i should ass .5,.5?
You gotta plug your current rb.velocity.y there so it keeps the vertical velocity```cs
// ...
moveDirection = rotation * moveDirection;
Vector3 newVelocity = moveDirection * speed;
newVelocity.y = rb.velocity.y;
rb.velocity = newVelocity;
yes
ok let me try
can i use vector2 instead of vector3 with physics.raycast?
or am i just not even understanding the concept correctly
well yeah you need Physics2D version
for 2D colliders
Yes, in fact the 2D version expects Vector2's
https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
my game is 2d
they are interchangeable btw though
i did 😭
looks fine, the gap just needs fixing with blockSize
when you pass a vector3 to a vector2, its valid because the z just gets 0d out
yes i should make the gap less
yes blocksize is probably 1
this is my goal
if thats default cube
a grid?
before i make my raycasthit, it makes sense to make a ground check first right? @rich adder
yes, i am making it like this because i want to be able to work on these cubes
understood
there will be things placed right on top of that and i will use the array for the pathfinder (at least i hope)
look into making the cube an actual Object
You would separate your visuals from code there
wdym ? do you not have a groundcheck
no i havent made one yet
im about to try to make one right now
ohh then yes make one first
why?
i just need a private bool and the use of tags right?
so you can easily reference that position,clicks etc. unless you have a 2D rapresentation of it in code
you don't need tags
Use layers and put specific things there
ok i will do it
i cant just use the velocity?
oh
use velocity for what
like if my velocity is more then 0 on the Y axis then I am airborne
then for isGrounded would be false
right?
if you do that there is no point in raycast
I wouldn't rely on that if you're gonna use a raycast
no you would only need the !isgrounded boolean
also grounded is not guarnteed to be rb.velocity = 0
well do i need a raycast?
as it fluctuates when ur on floor
i thought the raycast was so i dont stick to walls
yes but can be used for grounded
okay just to clarify, I need a raycast for a ground check?
To clarify, you need a cast of some sort, it does not have to be a sphere.
Casting a ray into the world gives you back information. The shape you want to use, be it a ray, a sphere, a capsule, etc. is up to your usecase.
i think i will use raycast, in order to do the ground check with this, i need to put the max distance of it to a small number though right?
use the documentation
but yes and no
depends on how large/tall your character is
you would preferably make it a [SerializedField] private float so it can be changed via inspector
my character is like 30 pixels tall or something
i forgot
i made it in photoshop
can i show you in dms what he looks like
thats okay you do not need to
i just meant like if you wanted to see 😭
do this if you are unsure #💻┃code-beginner message
what does "public static" mean in this
public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);
its the same variable of a class thats created i believe
static meaning you can call the method directly from the class , it doesnt belong to any instance
Physics2D.Raycast
instead of
Physics2D physics2Dclass = new Physics2D()
physics2Dclass.Raycast(etc..```
wait bruh i just realised, i need the ray to be casted in the direction im walking, so dont i need to make a code to recognize which direction im facing too?
depends , if you did it correct, ideally your transform.right would always be forward
a static method can be called from any class. it does not need an instance of that type . . .
Yes, often in platformers (is this one?) you store that in a bool like isFacingLeft
also you would make the raycast yourself and fill in what you need from what it asks
yes I am trying to make a platformer
my platformers always have transform.right as forward
but yeah a bool can work to track
it really depends on how you made it facing in the first place
no
both are good
as long as things work, there is never "better than other" (aside from writing code smells ofc lol)
whats good is that it works.
everything else is preference
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(Interactable))]
public class InteractableEditor : Editor
{
public override void OnInspectorGUI()
{
Interactable interactable = (Interactable)target;
DrawDefaultInspector();
if(interactable.useSingleInteraction)
{
interactable.useOpenInteraction = false;
}
if(interactable.useOpenInteraction)
{
interactable.useSingleInteraction = false;
}
}
}```
why isnt this letting me set the bottom bool?
why does transform not work here
RaycastHit2D hit = Physics2D.Raycast(tranform.position, Vector2.down);
because you typed it wrong. have you configured your ide
Is there a way to access my prefabs when they are not in Hierarchy? I want the changes to apply to all future prefabs
nvm found it
you can yes
it says the name transform does not exist in this context
I went to "Open" thats right, right?
prob not
we told them already
my message is blocked by this server apparently
Openn ?
idk the regex is weird sometimes the detection stinks lol
What is a tranform
oh whoops i spelled tranform not transform
I clicked on "Open" in the Inspector in the Top Right corner and i could edit the thing. Is there a better way?
thats the way to do it yes
i misspelled and forgot the s
please configure your ide, it would easily avoid this
Yes, so you should look closely at stuff underlined in red
i have it configured
i didnt realise the typo because when i hovered over the red i was trying to read what it said and when it said it doesnt exist in this context, i thought i was using transform incorrectly, i didnt know that i had misspelled it. now i know i guess
normally you type tran it already shows transform lol
it used to, until unity 2022 where it forces it into TransferFunction or something 
yes it does, im just trying to get in the habit of actually typing it so i can learn it, im only 3 days into learning unity so far, so all of this is very new to me
ahhh shitee lol some new stuff ?
gotta check again lol
yeah this thing apparently https://docs.unity3d.com/ScriptReference/TransferFunction.html no idea what this even is
ok just making sure lol cause configured IDE is needed here for help
yes i am 10000% it is configured, sorry for the confusion
so with all that out the way, this code should theoretically shoot a ray towards the ground wherever my postion is right?
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down);
yes but you probably want to start using layers etc and actually use the raycast hit
so now i can make an if statement using the "hit" right?
Ahh yes, the electro-optical transfer function
RaycastHit2D iirc returns null if not hit for 2D
but yeah still use layers, its one of the params
no, it's a struct
whats iirc
if i recall correct
oh does it not have implicit cast or something?
nope
it has an implicit cast to bool, it doesn't return null. hit.collider would be null and that null check is what the implicit cast to bool does
2D raycast hit has implicit bool cast
also whats null
ahh okay I remembered something like that but was fuzzy
null means nothing?
yeah
correct
no reference or doesnt exist
i forgot to mention, i put this code into void start, right?
Do you want it to run once when the object is created?
well doesnt that line of code just make it so i can refer to it as "hit"? if so than yes i think so
note that start runs one time, im not sure what your context is but maybe put it in update if you need it more than once
Normally you'd want to dynamically cast these rays multiple times during gameplay
yes for a ground check you don't want to do it just once 😛
i know how the voids work, my problem is that i dont know if i need it once or constantly
i know how the voids work
Self-defeating sentence
i just need someone to clarify to me that that code just makes it so i can refer to it as "hit" or if it doesnt
Well, you could need a onetime check if you wanted for eg to snap object to the ground once it's created
eg
isGrounded = Physics2D.Raycast(transform.position, Vector2.down);
but this now will Detect Anything including the player or maybe triggers which you might not want for solid grounding, so we use layers params
so then thats when layers come into play?
It will cast the ray and store the result in the hit variable.
ohhh okay so it needs to be in Update
You can freely use that result whenever you want to know what the result of that hit was
layers is just an extra filter basically to filter specific colliders fomr ever being calculated
so its constantly checking if i am on the ground or not right?
So putting it in start would mean you could very easily know if the object started on the ground
ideally in update yes
but that's not particularly useful information
you would put it in update
so this ground check now works?
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down);
if(hit.collider != null)
{
isGrounded = true;
}
else
{
isGrounded = false;
}
Debug.Log is the tool to check this
cant you do " if (hit) "
you could just do if(Physics2D.Raycast(transform.position, Vector2.down){Isgrounded = true;}
yes
or just do isgrounded = Physics2D.Raycast(transform.position, Vector2.down);
also like above i sent
isGrounded = Physics2D.Raycast(transform.position, Vector2.down);
also you would want a float for the distance variable in the raycast so you can change it
so its not inf
and a layermask as well
this is the same as "if(hit)" correct?
only in this specific cause because unity does an implicit cast
yes
dont need a layermask here though, depends on what his game is like i guess
hit in general is useful if you want spefic information like how tilted is the collider you hit, or maybe if it has other info you need
and if i named hit something different like, potato, then i would use "if(potato)" right?
if you want the raycast to not hit specific items, then use a layermask
which is the norm
yes the name is irrelevant
so I set the ground and player to the same layer and everything else goes to a different layer?
you wouldnt set the player to "ground"
all the layermask does it only hit "ground"
if you set player to "ground" you will always be grounded, which im guessing is not preferred
oh okay thank you
jeez this is all so complicated, literally just to get some movement in my game
you will get used to it
movement esp a platformer isn't exactly novice topic
took me months to wrap my head around movement, let alone raycasts
if you make a ground layer, you'd need to do the hard work of manually assigning every ground object in your scene to the ground layer, dont you?
thats not hard
like at all
usually I just keep it on Default and specific things are in other layers
just select all of your gameobjects you want and select the ground layer
assuming you keep everything organized in the hierarchy, just select the parent that contains all of your ground objects and do it all at once
doesn't that also select your non-ground things though? like enemies and stuff
select all the objects you want for the layermask
so no
thats pretty tedious tho
also I dont know why but in unity, in my console its saying that "the feild 'PlayerMovement.isGrounded' is assigned but its value is never used" but it is being used because i debuged if my player was touching the ground and it says im touching the ground, which would be impossible if isGrounded wasnt being used, unless I am wrong
wait until your scene contains tens of thousands of objects 😄
What's the alternative?
show the full code
is it because my bool is private, and not serialized?
you would most likely copy and paste most of them
so no
show code
that is irrelevant to the warning. show the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
public float jumpForce;
private bool isGrounded;
private bool facingRight;
[SerializeField] private float rayDistance;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down);
}
void FixedUpdate()
{
rb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb.velocity.y);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(new Vector2(rb.velocity.x, jumpForce), ForceMode2D.Impulse);
}
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, rayDistance);
if(hit)
{
isGrounded = true;
}
else
{
isGrounded = false;
}
}
oh my..
and as Ash stated you could just put them all under a parent and literally assign the parent "ground" as well a children, and it will make all children the "ground" layer
and where exactly are you using the value?
so no its not hard
what is that local raycast inside the Start doing
just raycast on all layers and then exclude specific layers you dont wanna hit with it
that is assignment, not actually using it
you know, like the warning said. you are assigning it but never using it
well how do i use it then?
How do you want to use it
i thought it was using it?
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
🥄
Where?
using it for what
Where does your code do anything different based on whether isGrounded is true or false
ohhhh
Yeah. I usually have a separate ground/map/scenery layer but I also include the default layer in case I forgot to assign the scenery layer to something
wait i think i solved it
{
if (Input.GetKeyDown(KeyCode.Space)&& isGrounded)
{
rb.AddForce(new Vector2(rb.velocity.x, jumpForce), ForceMode2D.Impulse);
}
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, rayDistance);
if(hit)
{
isGrounded = true;
}
else
{
isGrounded = false;
}
its up to preference because most likely is you have 10,000 objects they would be under a parent anyway
#💻┃code-beginner message
you dont even need those if statements for the grounded boolean just do
isGrounded = Physics2D.Raycast(transform.position, Vector2.down, rayDistance);
For a 2D raycast you'd need to cast to boolean because it isn't actually a bool, it just casts to one
nah, it does have an implicit cast
can i just write isGrounded = hit
Many why is 2D so goddamn weird
why
so you can do isGrounded = Physics2D.Raycast(transform.position, Vector2.down, rayDistance); in 2D?
neato burrito
@sand snow Can you make a thread please so you don't occupy this channel.
i'm pretty sure they did that to sort of be on par with a 3d raycast which returns a bool. Why they didn't just make the method return a bool with an output parameter like Physics.Raycast is beyond me though 🤷♂️
i suspect they likely made the change well after they actually implemented these systems though so it was probably just to avoid breaking changes
why can i see through walls when i get really closer
probably camera clipping plane
fix?
ill look into it thx
you can press F to focus on it as well
it should fix it a bit
thats the camera clipping plane like nav said
so just make all the colliders bigger?
colliders worked for me but thanks 👍
okay ig
It's working! Thank you very much!
hits = Physics.RaycastAll(ray, defaultInteractionDistance, defaultObstructionMask, QueryTriggerInteraction.Collide);
instead of defaultObstructionMask what was that thing for every layer
something like -~
i'll just use Physics.AllLayers
Hello
I'm having difficulties making an inventory system in Unity
Can someone tell me how to make one?
Defaultraycastlayers?
what difficulties
show your code and the difficulty
Don't know how to make inventory
have u checked out tutorials on youtube
My team made a pickup and drop system, but we have no idea how to make an inventory system
No
No
I didn't
it's still better to use Physics.AllLayers as that is much more readable
i guess i'll see you here for another few months then
yeah i know
i didnt know that existed
i thought i was only the -1
~0 would work too as that is also equivalent to -1
A basic Inventory is only a List of Items which you add and remove to/from
Yes
Is there a cyber role?
https://hastebin.com/share/oviwabulig.csharp
what could I replace MonoBehaviour with?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
for those curious, the reason this is all layers is because it is all 32 bits flipped to 1. 0 would be all bits at 0 which is no layers, and since negative numbers are stored as twos complement, -1 is the sign bit at 1 and all of the other bits also at 1
i kind of want to just be able to slot in a script
any script
the actual class
of the script
but what if i want to use several different scripts
then it needs to either be a shared base class or interface
MonoBehaviour would be too broad because all of your components inherit from that, so you'd want to create either another class that all of the possible items inherit from, or some interface that they all implement
that is how you do it
how does Physics.RaycastAll store the hits
apperantly its in order from the closest to furthest
so hits[0] would be the closest object right?
no, the order is random
Just sort the array yourself. or if you just need to find the closest, a simple for loop and a single variable with the index of the closest one found is all you need
Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));```
is that fine?
i mean, it really depends on what this is going to be used for. do you need it to actually be sorted? and do you need a new array every time you call this or could you use the nonallocating version
i need it to be sorted
cause i need to get all the hit gameobjects before a specific one
and i can only do that by distance
So it seems like what you need is the closest result, not a sorted array
wdym by "before a specific one" is this "specific one" known before the raycast? because if so, just cast between those objects and you don't need to sort at all
im making an interaction system where each objech has its own obstruction mask
and its own interaction distance
so first im doing a raycastall to get all the results
and the distance is 5
even tho the defaultInteractionDistance is 2
because some object might have an interaction distance of like 3.5
which would be bigger than the defaultInteractionDistance
then im gonna have to loop through all the hits
and find the closest interactable object from the player
and check all the hits before that interactable object
if their layer is inside the currentInteractable.customObstructionMask
and then do the distance calculations
but thats the easy part
OnMouseExit
that is not the opposite
it is
u trying to detect when mouse is not over?
yes
so just flip a bool in onmouseenter/exit
So you want to call something every frame you are not hovering?
now that you mention it
i should reconsider
ill prob just use a bool and then mouseenter and mouseexit
what boxfriend said
how do you make these public? i thought it was just public before void but that throws an error
what is the error
those methods are nested inside of another method
these scripts are meant to work together to let me pick up and drop items, but whenever i try picking up any item that isnt the latest one created with the script attached it doesnt let me drop it
its rly weird cos the debug.log that ive dropped it shows up in the console, but nothing else happens and it stays parented and kinematic
https://hastebin.com/share/uxuzutemer.csharp
sorrry for reposting it but i genuinely have no idea how to fix it ive tried everything
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Idk if this would be a code thing but I assume it would be. Is there a way for a render texture/camera to only show things inside of a collider? Like if there's a sphere collider it hides everything outside of that sphere. And if a part of the sphere is hidden its hidden from the camera/texture as well.
Most of this code really belongs on the interactor, not the interactable
but what if i wanna interact with something that isnt an item
But basically, all those Updates are running at the same time
Make an Interactable script
That just fires an event or something
It doesn't matter what the actual thing is
OHHH THATTSS WHAT I WAS DOING WRONG
TYYY
private void MovePlayer(){
Vector3 movement = Vector3.zero;
// Calculate movement based on input keys.
if (Input.GetKey(forwardKey)){
movement += cameraObject.transform.forward * moveSpeed;
}
if (Input.GetKey(leftKey)){
movement += -cameraObject.transform.right * moveSpeed;
}
if (Input.GetKey(backwardKey)){
movement += -cameraObject.transform.forward * moveSpeed;
}
if (Input.GetKey(rightKey)){
movement += cameraObject.transform.right * moveSpeed;
}
// Set the Rigidbody's velocity for snappy movement.
rb.velocity = new Vector3(movement.x, rb.velocity.y, movement.z);
}```
So I am making a player rb follow the player, problem is, movement is always towards where the camera is pointing, how do reset the z rotation on this reference to the camera object here, so it moves where the camera would be pointing at 0 z-rotation
the rb doesn't rotate with the camera, so I can't use it's transform as a reference
Not sure I understand, do you want to rotate the movement horizontally only?
this is just plain old wasd movement
Oh didnt see you posted code somehow
the issue is, it adds velocity relative to camera position, so if the camera is looking up, w loses all velocity
Before you use tha camera's forward, set its Y to zero
Then normalize it to make sure it is 1 length
kk, how would the y affect it in this situation? I would have thought the rotation on the z axis (when the camera looks up) would be the culprit
Z axis is normally the "twist" or "roll" axis, I doubt it is relevant here
Maybe you mean X axis rotation
Which is normally up/down
yes , sorry
x axis lol
how do i reset its y value without actually changing the gameobjects y value
can I hold a vector3 reference and then do it
Make a new vector3 from it
kk
Yeah, or well it's not exactly a reference but a copy, since Vector3 is a value type and not a reference type
Make sure to normalize it after removing the Y though
Value types are always passed as a copy
ah c# things I guess lol
weirdddddd, I haven't seen value types in java or any web languages
just a c# thing I guess
Or it's called something different in those languages
Broadly speaking:
-classes (MonoBehaviour, custom classes etc.) are reference types
-structs (Vector3, Quaternion, etc.) and primitive types (int, float) are value types
Seems to be similiar in java
what is a struct xD
Things defined with struct instead of class
kk, i have some c# learning to do
I never heard the term value type in my java classes
before i start on a scale from 1-10 how difficult is it to code enemy movement, with them following the player?
just following the player, to start with
there's types, idk what value type is
Pretty straightforward with NavMeshAgents, assuming it's a 3D game
there was instances of objects, references to them etc
And assuming that you have obstacles and need pathfinding
In Java, if you did:
int x = 13;
int y = x;
x = 7;
System.out.println(y);
What would you expect to see?
13
your casual tone makes me feel more confident to start on this bit
thank you
So, you are familiar with value types.
Nope, still called value types
what! xD
Primitive types are value types, but they're not synonymous. Like how all squares are rectangles
wrinkling my brain
I remember writing BigInteger classes, making abstract types lol
so value types is just another name for primitive types
Looks like they are
private void MovePlayer(){
Vector3 movement = Vector3.zero;
Vector3 camera = cameraObject.transform.position;
camera.y = 0;
// Calculate movement based on input keys.
if (Input.GetKey(forwardKey)){
movement += camera.forward * moveSpeed;
}
if (Input.GetKey(leftKey)){
movement += -camera.right * moveSpeed;
}
if (Input.GetKey(backwardKey)){
movement += -camera.forward * moveSpeed;
}
if (Input.GetKey(rightKey)){
movement += camera.right * moveSpeed;
}
// Set the Rigidbody's velocity for snappy movement.
r```
How do i qualify camera with a type name?
What do you mean? The type is Vector3
error CS0176: Member 'Vector3.right' cannot be accessed with an instance reference; qualify it with a type name instead
I'm trying to expand on the A*pathfinding system, and I'm currently trying to get the AI to do 2 things. Only follow the player when within the grid, and I want the AI to return to it's start position when the player exits range. Any help or suggestions would be appreciated.
Is it your custom A*?
These problems don't seem really related to the pathfinding itself though
Just a couple of if-statements
Or events
private void MovePlayer(){
Vector3 movement = Vector3.zero;
Vector3 camForward = cameraObject.transform.forward;
Vector3 camRight = cameraObject.transform.right;
camForward.y = 0;
camRight.y = 0;
// Calculate movement based on input keys.
if (Input.GetKey(forwardKey)){
movement += camForward.normalized * moveSpeed;
}
if (Input.GetKey(leftKey)){
movement += -camRight.normalized * moveSpeed;
}
if (Input.GetKey(backwardKey)){
movement += -camForward.normalized * moveSpeed;
}
if (Input.GetKey(rightKey)){
movement += camRight.normalized * moveSpeed;
}
// Set the Rigidbody's velocity for snappy movement.
rb.velocity = new Vector3(movement.x, rb.velocity.y, movement.z);
}``` Okay it works great until the camera points at exactly 90 degrees, then all movement stops
should I just give each vector a minimum value it can be when pressing a certain key
what was the command to check i had visual studio code and unity setupo proper;ly?
there is no command specific, you have to check if underlines errors / shows all your unity components/classes
i mean the one in the discord
that shows the guide
!vscode
if((currentInteractable.customObstructionMask & (1 << currentHitTransforms[i].gameObject.layer)) != 0)
{
}
// This objects layer is not in the accepted layers of the interactable
else
{
isBlocked = true;
break;
}```
how do i reverse the first statement
cause i dont need it to be true
do i just wrap it in extra brackets and slap a !?
would that work
Well, give it the ol' logic brain: Right now, you're checking if X AND Y. Meaning any time both X and Y are true, the condition is true. What is a condition could write such that it returns true in the other three cases?
X | Y | Result
T T T
T F F
F T F
F F F
What logical combination of X with Y would result in
X | Y | Result
T T F
T F T
F T T
F F T
i dont understand what ur asking me
I'm trying to explain how you'd use boolean logic to reason this out yourself, instead of just being told the answer
well yeah but what i wrote works
The first truth table is what you've current got. The second is what you (presumably) want
this
how would i go about getting the x and z position of the mouse in the 3D world?
thats what i did
oh use the or
im comparing two different things tho
so i cant
wait i can
but thats gonna be a long ass line
and the code is going to have to compare both
If you're checking two different things, then you're not asking for the inverse of a condition, you're asking for two conditions
this is in a loop already
the value of Z has no bearing on the result of X AND Y
I have a reeeeeally stupid question that I can't seem to get my head around.
I have an array of floats and I need to increment the value of a float based on it's index.
public void UpdateOreCount(int indexID, float oreAmount)
{
ores[indexID] = ores[indexID] + oreAmount;
oreAmountText[indexID].text = oreAmount.ToString();
}
This is my function, first time it runs, it adds the oreAmount value and updates, but subsequent values don't get added.
What am I doing wrong? (And yes, I completely believe that I'm being a complete spanner. lol.)
You're setting the text to oreAmount. you probably want to set it to ores[indexID]
So, you're setting the text at that ID to the amount you added, not the new total
Oh bloody hell. lol. Thank you. Told ya I was being a spanner. 🙂
any idea what im doing wrong from lines 55 to 70? i want to convert mouse position into its real world position but instead of going where i click, the units go elsewhere https://gdl.space/epulezusoc.cs
Can someone help me with this
private void MovePlayer(){
Vector3 movement = Vector3.zero;
Vector3 camForward = cameraObject.transform.forward;
Vector3 camRight = cameraObject.transform.right;
camForward.y = 0;
camRight.y = 0;
// Calculate movement based on input keys.
if (Input.GetKey(forwardKey)){
movement += camForward.normalized * moveSpeed;
}
if (Input.GetKey(leftKey)){
movement += -camRight.normalized * moveSpeed;
}
if (Input.GetKey(backwardKey)){
movement += -camForward.normalized * moveSpeed;
}
if (Input.GetKey(rightKey)){
movement += camRight.normalized * moveSpeed;
}
// Set the Rigidbody's velocity for snappy movement.
rb.velocity = new Vector3(movement.x, rb.velocity.y, movement.z);
}``` Still trying out how to make the movement based off the camera as if it's x-rotation was 0
because when the player looks directly 90 degrees at the ground or sky, there's no movement, because forwards is straight down or up
is there a way to override GameObject ToString() method? I want it to show something else other than name. as an extension method or something?
.name is a string
What are you using to give the mouse a 'hitpoint' in the 3d world? You would usually use a plane.
im using a cube for the ground
i think ive spotted the issue though
the y and z values seem to be flipped
swapped* i mean
i dont see why u couldn't use an extension method
gameObject.ToYourCustomString();
instead of moving via camera transform i would use a "orientation" object which would rotate with your player left and right but not up and down
AKA make it a child of your player
not camera
That's what I was thinking, but I just didn't want to add a ton of random objects in the scene following the camedra
camera
But I guess I could convert that object to the player model eventually
it would be a a child of your player which should rotate when you rotate your camera
sry. i shouldn't have mentioned extension methods -> I led you in the wrong direction. I'm using a generic class which i'm instantiating with GameObject type at runtime. for debug purposes i need to Debug.Log stuff. but in code I don't know yet that the class will use GameObject as type. hence i wanted to override GameObject.ToString()
Yeah I understand, thankyou. I wil ldo that then
oh, thats a bit more complex than i was thinking yes.. lol
ya, not sure im savvy enough to know bout that
imo using abstract classes and overrides and stuff are code-general ++ but i could be just a newb 🤣
yeah. stack overflow sugested that i subclass GameObject, use that and override my ToString
aye, that sounds solid
well, i consider myself begginer cuz i started tinkering with Unity 2 weeks ago
well ur the odd crowd. lol
Wdym by "instantiating with GameObject type"? Is GameObject the generic type here?
yeah
Like YourClass<GameObject>
yep
osmal entering the ring 💪
Thanks, that was extremely easy, and made my code much simpler lol
@rocky canyon Hey! I have a business inquiry. What’s your email?
Can you show a code example of what you roughly would like to do?
yeah np my dude
Unless you already found the answer
Thank you!
You mean like making a concrete class: class TheClass : GenericClass<GameObject>?
I kinda wanna make a bunker building game where you have to try and reinforce a base as like a welder dude, and zombies try to destroy it
what yall think lol
sounds neat if implemented well
and then move it towards a rust sortof game once I have ai mechanics down
but not code related best go to #archived-game-design
kk
pretty much i found the answer. but the code looks like this now:
class Algos<T>{
genericFunctionAlgorithm(...){
List<T> myArray;
//do stuff
Debug.Log(myArray.ToString());
}
}
____________________
some script with class:MonoBehaviour
...
void Start(){
Algos<GameObject>.genericFunctionAlgorithm();
}
the answer I think i found tells me this:
class MyGameObject : GameObject{
GameObject myObject;
public override string ToString(){
return myObject.transform.position.x.ToString();
}
}
____________________
some script with class:MonoBehaviour
...
void Update(){
Algos<MyGameObject>.genericFunctionAlgorithm();
}
Please link me to the answer because you cant inherit from GameObject, that class is sealed
well i didnt try that yet. the stackOverflow answer didnt mention sealed classes as it wasnt about Unity GameObject specific question. guess i'm stuck. or find another way to debug
Do you want to debug.log each item in the list?
yes
this is what i get for working with generics. i had to pretend i'm smarter, didnt i
In C#, every object has a ToString method so the generic type T is guaranteed to have that too
You can do this: cs foreach(T item in myArray) { Debug.Log(item.ToString()); }
Debug.Log(item) should work too
in my case it will print the GameObject's name. but i wanted something else out of the GameObject.
Okay, I think you'd need abstract/virtual and override methods then
Bit above beginner level but...cs // Base class protected abstract string GetInfo(T item); // Derived class protected override string GetInfo(GameObject item) { return // ... whatever info you want from the gameobject }
And then you'd call GetInfo(item) instead of item.ToString() here
yeah. makes sense. thx a lot
The abstract method could also be a default virtual implementation instead:cs protected virtual string GetInfo(T item) => item.ToString();
Np
please tell me nav meshes arent as complicated as to actually need 54 videos explaining how they function
im seeing different videos of varying times
one at 8 minutes, one at 10, one at 40
That guy has decent videos, but 54 videos sounds like way, way too much
54 videos is just too much 😭
at that point just write a book and i'd rather read that
Here's an alternative https://learn.unity.com/tutorial/unity-navmesh
thank you 🙏
i thought looking nav meshes unity on youtube would just show me the unity account but
nope
oh wait this is actually really cool
so idk if my issue is with the navmesh but the slime enemy in my game isn't moving but still tracks the player an plays the animation accordingly. Been trying to fix this since yesterday but to no avail, can someone please let me know the problem. I'll past the enemy inspector and the code below so you guys can check it out
has anyone done any voxel like projects in unity?
probably
7 days to die comes to mind
yes
Did i do some mistake?
i == itemIndex2 will be true
oh my bad my bad it should have been MainItems[i]
i really dont know how this worked all this time
It works fine when you're activating the object. Not so much when you're trying to disable it
Is it possible to instantiate something from one scene to another?
iirc you can only spawn inside an active scene
so you can technically do it if you do some additive stuff
I have multiple active scenes I wanna spawn some stuff from the player/manager scene to another one is that able to be done
do you have a reference in the other scene of a gameobject/transform via singleton? You can just spawn it as child without dealing with active scene limitation
Not via singleton is that how I should do it
I'm just making you aware of what the options I know are, how you do it is your choice ofc
having a singleton ofc is much easier than messing with additive and changing active scene to spawn something
you need a way to get the reference though hence easy singletons (cross-scene references)
By active scene they mean the first scene loaded normally. Everything else loaded additively is just gonna be added to the first scene iirc.
Im not extreamly experienced I dont know if you remember helping me in the past but you have so learning new ways to do things helps tremendously. I dont know much ways to do things. I think the way I get references is a little jank not sure but it works. Singleton is 100% the right way to do it makes sense now
on note of what dlich said you would need this to switch active scenes if doing additive
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.SetActiveScene.html
singleton will be the easiest probably , but first evaluate why you need to do this in the first place
usually when I have to jank or do something kind of against the normal workflow, something in the design might be wrong
I have 2 scenes at the start main menu and player/managers then I have level 1 spawn then I want things from players/managers scene to instantiate things in the level 1 scene.
I am talking about the way I refrence other scripts 90% if the time I dont think its right but it does the job
well yeah you don't want to overuse singletons, keep it for only specific manager
How are you loading the 2 scenes?
Awake
so one per manager?
not necessarily no
you dont want every script to talk to every separate message IMO thats bad pattern
you should only communicate to 1 manager that talks to its own managers it manages
this is how Im refrencing things normally
private WaveManager wavemanager;
void Start()
{
WaveManagerGO = GameObject.FindGameObjectWithTag("WaveManager");
wavemanager = WaveManagerGO.GetComponent<WaveManager>();
}```
Awake doesn't load scenes.
Okay good thats what I thought just one for the big manager object
I meant in awake this is the code
{
SceneManager.LoadSceneAsync("Player.Manager", LoadSceneMode.Additive);
}```
yes this is the pattern I'm talking about. Worth a read or bookmark this site, very useful to learn
https://refactoring.guru/design-patterns/mediator
Will defently look into that
Sorry, how to add more functionality to the Wiggler script so that the user can specify movement in all directions (not just the Y axis)
make more variables?
i download everything and still having an issue
like this?
How can I get rid of this giant annoying blue block, and also make it, so my UI is always rendered, so it doesnt dissapear behind blocks
nvm i figured out the clipping part
Thankyou good sir
Now how do I make the GUI not this large so I can edit it lol
ability to change it's transforms are locked in overlay mode
Pixel space and World Space are two different things, you have click the 2D button option the select the canvas and press F to focus it
also canvas adapts to the screen resolution / size
WHAT
thats crazsy
Thankyou good sir, holy moly, I did not know about focusing elements xD
yes, check out pins in #📲┃ui-ux there is info there how to anchor and do everything properly
could someone help look at my unity build profiler with me to figure out why its so laggy despite it running seamlessly within the editor?
Are you running the profiler remotely?
They are crossposting shamelessly and already have their issue solved in #archived-code-general
🤦
any good 3d hitbox tutorial u recommend ?
Hi, I am writing this simple movement script and keep running into a weird issue.
When I am on the ground, it's all good, however, if I am in the air(be it by jumping or simply dragging my player up), I am unable to move.
Direction is fine, acceleration being added to the _rb.linearVelocity in the Move() function is fine(logged both) and I am suspecting the ApplyGravity() function but I am honestly not even sure at this point.
Could somebody help me with this one because I am out of ideas.
https://gdl.space/yiyixanise.cs
depending on what you need, most likely unity docs
im trying to do like a fighting game
look into colliders, box casts, overlap box etc.
each one serves a slightly different purpose
what would be best for fighter game like smash
it depends.
if you need physics interactions etc. then collider components+rigidbody is the way to go.
if you are looking for a way to detect when say a bullet hit a player, then using BoxCast or OverlapBox on the bullet and collider on the player would be a decent choice.
read what they do on unity docs, they have great examples and explanations and pick what works for you.
https://docs.unity3d.com/ScriptReference/Collider.html
https://docs.unity3d.com/ScriptReference/Rigidbody.html
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
https://docs.unity3d.com/ScriptReference/Physics.BoxCast.html
https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html
you would usually combine these to achieve best results
isee ty
Does commenting out friction fixes it?
iirc no, but let me test that rq
I think it does, odd, I was positive I didn't take y axis into account when it comes to friction, thanks for pointing it out!
guys im new to unity where is the assets folder its normally next to the console but i cant find it
do you see this anywhere?
you might've closed the project tab
I just made a toggle buildmode, and primitive objects get created, im stoked
ctrl+5 or open it as shown in this pic
THANKKKKSSS
How would you guys think I should go about making a grid system for building in a game
var newVel = vel.normalized * speed;
During the jump, the y component of velocity is presumably way bigger than the other ones, so normalizing it would cause the x and z components to be very tiny.
oh, I completely missed that one 🤦♂️, thanks!
I just discovered IEnumerators as coroutines, and I wanted to try making a camera shake effect, but I can't make it work.
I am new to this, some help pls?
yeap, works flawlessly now
It just doesn't execute the method when I call it, I am doing something wrong?
do you get any errors, such as NullRef?
None
mind debug logging in the on collision enter?
Check the documentation on how to start a coroutine
could be that but wouldn't it just execute as a regular function and at least throw a debug log?
I could be mistaken, haven't done that in a long time
Like this?
sort of, you can pass in the actual coroutine:
StartCouroutine(cameraShk.Shake(10, 10));
nice
i made a script that generates a quad, and now want to make its surface a png, and am going crazy trying to figure out how to make google tell me the answer lol
any advice/links?
Show your implementation?
did some more searching, found this solution online(?)
What component are you using to generate the quad? Show your implementation of the quad.
- i created a default material titled "WallTile"
this seems to work good enough for now™️, i'll probably just roll with it
Move the contains if statement to the top of the method
Atm it is making that check every loop iteration
considering that if statement relies on both variables declared in the foreachs im not even sure what you mean myself.
Oh wait. I’m a dumbass 🫠
one quick thing i notice is that the Resources.Load is done everytime you want to create a wall. That can be done once in awake/start and be cached then reused here
Resources.Load isnt so cheap
ah, makes sense. tyty
Mornin all.
https://hastebin.com/share/sipefajosu.csharp
I have this script that is spawning objects into the world, checking position, if conditions are met places object on the terrain surface, if not, repositions and checks again.
I know it's pretty inefficient, but I can't really think of another way of doing it. The problem I'm having with this approach though is that I'm causing a stackoverflow because the amount of recursion involved.
Would anyone know of a way to prevent the stackoverflow, or a different method of placing the objects where I need them? 😕
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What happens if you reach the max xyz coordinates of the scene?
I never do, the objects are being spawned in 'chunks' (just one chunk at the moment)
the farther you get from the origin the more the game spazzes out
Single Chunk with visual representation.
Dedicated question 🙋
Hmm ? Sorry, not sure what you mean?
Oh sorry, were you just asking in general? Not related to my question?
Sorry, I think wires got crossed. (I've literally just woken up. lol.)
But yeah, anything above 10,000 units from center, floats get screwy
could you go into a bit more detail about what the goal is
I think I may have it figured out. But basically spawning a load of rock objects on the surface of a terrain. But doing it in 'chunks' (see image I posted).
raycast is certainly the right way to go about it, but i dont really understand why you're moving the object before you know where you want it to go
If you're aiming for placing on the surface, why not just sample a bunch of random points from an arbitrary height, and then distribute your rocks among those points
I've changed from raycast to SampleTerrainHeight for the moment. And yeah I'm reworking my code atm (I wrote it last night when I was very very tired. lol.
terrain.SampleHeight sorry.
sounds good
I've fixed the memory leak I was causing. I was recursing back and forth between two methods which was crapping it all out, so just reworking everything into a single method.
Can you pass through a parameter with a coroutine?
into a coroutine, yes, out of a coroutine, no
I'm sure it's an obvious solution, just couldn't get it from the wiki/discussion posts
coroutines are started not called.
see StartCoroutine
also your signature is incorrect, the parameter needs a type
Yes
Hello
If it's possible to put the sprite a child in front of the parent sprite ?
not always, depends on what you changed
Just some order of execution in a for loop
Thank you, this helped
did not take into account type errors
it would have been more obvious had you not used var
yea, a lot of posts bounce between different ways of doing stuff and I'm still new to types
reading about it though
take my advice, never use var, always use the type correctly
no, it's because you have to
https://docs.unity3d.com/ScriptReference/Renderer-sortingOrder.html but do it on the component not script
possible infinite loop then?
I agree with this so much. The amount of tutorials/guides where people use var all the time. Just seems to me to be lazy coding.
Would seem so, it crapped out my pc so hard that it killed everything I had running. lol.
even as a very experienced C# programmer I never use var. For beginners it is just very, very bad practice because C# depends on the Type system and using var kinda negates the learning of that
Yeah, I'm trying to avoid videos since it spoonfeeds too much but a lot of posts do this as well
I've managed to make some cool stuff without any videos though, so I'm pretty happy
on a private learning project just to experience Raycasting and different ways of using it rn
Yeah I still have a loooooooot to learn, but even when starting out with Unity I noticed the usage of var and it made no sense to me whatsoever. And in my head surely using it would add (albeit a small amount) of overhead as it would need to figure out what the var actually is?
did you get a stack overflow?
Is there a good practice for storing lastTarget hit to reset the color when it's no longer being hit?
rn I'm just gonna store the variable on hit for lastTarget
Initially I did when I was recursing between a couple of functions, but I've condensed it down to one and seemingly fixed that, but just made some order of operation changes and it crapped out, so I'm assuming it returned. lol.
So just taking a few minutes away from looking at it, so I can look at it with 'fresher' eyes. 🙂
sounds like it, with infinite loop the program will hang but not crash, with infinite recursion the program will eventually crash with a stack overflow
Yeah, basically what I'm doing is Instantiating my object at a random position, checking the terrain height underneath it, if it's between a certain height range move the object to the surface, move on to the next. If the height isn't between the given range, move the object to another position and try again.
I know that it's horribly inefficient really (happens on start, so only runs once), but I don't know of another way to do it 😕
ouch. why not first make a List of all the positions which are valid and then use that list when you instantiate your objects
I am currently trying to make a movement script and now that i have my walking speed I want my speed to increase when i hold shift (like a sprint), how should I do this?
do I use a bool to see if I am holding shift and then an if statement?
I'm not entirely sure how to get the list of valid positions without having an object/transform to use as a position reference if honest. The list isn't an issue (list of Vector3's), it's just how to get those values in the first place to put into the list. lol.
no, you need to keep a copy of your speed variable. so origSpeed and currSpeed, then a simple if to check for shift can increase currSpeed and when you release set it back to origSpeed
so something like
if(Input.GetKeyDown(KeyCode.LeftShift))
{
currSpeed * orgSpeed
}else
{
orgSpeed
}
???
lets say you want to place objects between 0,0,0 and 10,5,10. just cycle through your terrain and store all positions of the terrain that fall into that range
is that supposed to be c# ?
yes
well it's not
how?
Yeah, I'm just looking at the TerrainData stuff now. Thank you 🙂
currSpeed * orgSpeed
orgSpeed
yeah so if iclick shift my current speed will multiply by my orgspeed, and if i am not clicking shift then it will just be my orgspeed
whats wrong about it?
mb
wait so which speed is supposed to be the "walking" speed
ohhh nevermind i get it
currspeed is the multipliar correct?
I also have a question what does *= mean
If you do not know what *= is then I suggest taking a quick C# course
also im not sure why but its not detecting when i hold shift, but the code does work because if i spam shift sometimes the value will change
i know it mean times what is equal to the right, its just i wanted to know like what it means
wait
that is what it means
my bad 😭
Still, it's never a bad idea to take a course
Show full code
its in void update if thats what you're trying to see
Still, show full code
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
public float jumpForce;
public float sprintSpeed;
[SerializeField] private bool isGrounded;
private bool facingRight;
[SerializeField] private float rayDistance;
[SerializeField] private LayerMask groundMask;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
rb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb.velocity.y);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
sprintSpeed *= speed;
}
else
{
sprintSpeed = speed;
}
// Jump mechanic
if (Input.GetKeyDown(KeyCode.Space)&& isGrounded)
{
rb.AddForce(new Vector2(rb.velocity.x, jumpForce), ForceMode2D.Impulse);
}
isGrounded = Physics2D.Raycast(transform.position, Vector2.down, rayDistance, groundMask);
}
}
You reset sprintSpeed back to speed on the next frame
it works it just doesnt detect when im holding shift for some reason
