#💻┃code-beginner
1 messages · Page 10 of 1
2022.3.3f works for me
but anything above .7f and I get Pink fonts
interesting
Yeah, what happened with your bug report on that. Any response?
I only got a "We've Received your report" email but nuthin further from there
God, how do I run Unity as a standard user? It runs it as an administrator every time, I haven't checked "Run this program as an administrator" In Unity or Unity Hub's properties.
you're not the first..
if you ever installed the Hub as an admin, it's probably going to be stuck that way
If I click "Run Unity as the standard user" it just prompts it again and again and... Yeah keeps prompting it.
something to do with your Windows I think running you as "Eleveted" admin user instead of regular user with admin rights
saw it on unity forums somewhere, fuzzy on details rn
Well if I just run it with an admin, will there be any problems or something?
Unity says there will be, I'm not certain ..
I never had this issue.
yes, look at which account you're signed into
Your PC should have two accounts by default: a user account and the Administrator account
As the user, you can still elevate to do things that require admin privileges
I don't understand, I have just one user account, it's me and it's the Administrator.
well, there's the problem!
"Run as Administrator" means that, if you aren't currently an admin, the program will elevate to gain admin privileges
(probably including that UAC popup)
but if you are the admin already, that doesn't matter
this long ass thread I think
https://forum.unity.com/threads/disable-unity-is-running-as-administrator-popup-warning.1293657/
So if I run normally but in an Admnistrator account, it will run the Unity as an Admin, no matter what we do, right?
(You do this so that normal programs can't just blow up your entire computer)
Right. "running it normally" just means you don't try to elevate
Well I think it just disables the popup, but the Unity still runs as an Admin.
its not a fix
read the thread
It's been many months using Unity and it always opens as administrator even though I didn't mark it to be. I have crashes even in the LTS version, which cause almost all applications on my PC to stop working, I thought it was related to RAM, but I have 32 GB and it happens even with a very small scene open in the background.
I don't even know what "elevate" means, sorry.
it means to gain more privileges
when you run an installer, and you get that UAC prompt, it's elevating
(I am also not an experienced windows sysadmin, so i'm probably butchering the terms a bit)
is your UAC off ? @weary crystal
Ohh, well I didn't got an UAC prompt.
Because you are an admin already.
You don't have to do anything if you are already the admin.
you don't have to unlock the door if you're already home
I don't know, but my windows is not a normal one, it's "performance optimized" for gaming.
well that explains it..
probably messed with UAC
or turned it off
which causes these issues
I saw someone in that thread say this was an issue
This would have absolutely nothing to do with "gaming performance", btw
It's called Tiny11, I never had issues with something else though, I installed Python and used it for a while and many other dev things I don't remember.
a lot of "windows optimization" and "windows debloating" is like throwing a live hand grenade in your car's engine bay
maybe it was back in Windows 7 that these "minified" version mattered
or XP
I remember i had windows xp "black gaming edition"
if you have just one user, and that user is an Administrator, then unity is always going to be launched with admin permissions
because...how couldn't it?
Yeah, I think that's what Tiny11 is, it's just debloated, maybe some registry tweaks, I don't really think this could be the issue.
python isn't the same as unity
at all
thats like saying " I installed PHP with no issues"
I know but, isn't it one of dev things?
again: hand grenade in your car's engine bay
They both are "dev stuff" after all.
python just a language, unity is an engine
Make a new user account. Install Unity Hub as that user, install Unity, and you should be good.
You will always get this warning if your only account is an administrator.
Ok, what about Unreal Engine, Godot and GDevelop, I used them too.
they're not unity 🤷
they just happen to not complain if they're run with admin privileges
unity is mostly complaining for your own sake
a game engine runs a ton of random code, including a lot of code you didn't write
Is there anything else I can do? Or that's the only choice I got...?
if you are married to Tiny11 and you don't want to make a new user account, then you'll just need to click through the warning
Eh um, okay.
Yeah and destroy my 4GB RAM 💀
I feel like those "tiny" versions are just placebo for your PC
it doesn't change the hardware
they might disable some system services
(again, hand grenade)
yeah maybe 0.4% gains , who knows what the real life numbers are
Nah they decrease the unnecessary performance usage, I have compared both of them, I couldn't play Minecraft on normal windows but on Tiny it works smooth.
"I'm gonna remove my car seats to make my car faster" sure it works.. but doesn't change the engine being crappy
Damn bro, but yeah, that's what it is.
are u not able to make a regular user account and try that?
I can, I'll try it.
I "kind of" know how to make games but I don't know where to start, what type of games I make and all that.
then you probably need to start with something very small
i would look at what type of game you want to end on, pick the engine that would be best for that particular game, then start with a very basic game in that engine
this^
just dont make your first game Call of Duty or something llike that lol
like if you want to make a game that is best with Godot, start by making flappy bird in godot following a tutorial
Godot ?
I know what godot is just found it odd mentioning it to someone who just started unity lol
and godot is not easier than unity Imo
Bro, exactly me, I'm trying to make Call of Duty, I can make Flappy Bird btw, I made a Flappy Bird 3D, published on itch.io, set $1 price by mistake and lost my authentication, bam! The account's gone. Whoever pays, pays for God.
i’m saying: look at dream game, find out which engine is best, start learning that engine with basic game
Is there any modeler to make an SMG better than mine?
some people start with the very wrong engine, and get started down a very wrong path
one guy tried to make mario maker with kirby using python’s pygames. Very wrong decision
he was fucked before he started
true grit : you can make any game using any engine
the tool can be important but the toolmaster can open all doors
you can cut a 2x4 with a kitchen knife, but it’d be foolish not to use a saw
yeah like 2D in unreal
start in the right workshop
Damn true, bro's speaking facts.
Hey guys, a Z-fighting question.
I have two flattened cubes in unity, that are on the exact same table at similar position (as in picture), and since they are told not to collide, they instead start Z fighting. Which is not unexpected.
But since my game will have this scenario happening all the time (cubes overlapping each other), I need to solve how to make sure one is always infront (even if there are 4 or 5 overlapping cubes.
Is there a reasonable tutorial or way to make an hiearchy on what should be shown ontop? And avoid Z fighting.
Godot is good but has a few years before it can catchup to unity's 2D
lets not even mention 3D as its very...very early..
I made this, what's next, coding and I'm fucked.
the camera view / game style usually is not important to the mechanics you will be using, it all really boils down to learning the same systems..
eg. Raycasts, Inventories, AI etc.
Just gonna add some zombies, we kill them, do some parkour and yeah get to the end point.
Navmesh does most of the work for u in terms of basic AI traversing
Yup, thanks.
Hey I finally found a place to ask this question!
So I'm making a game where you can look at the side to rotate your camera, well the rotating works fine, but if you go to the side/boundary you can no longer turn back which is really annoying...
I decided to post the code in here:
https://mystb.in/ParticipantFundedImplementing
I attached my BlueBallCollision script to my player and I assigned the BlueBall tag to the Blueball gameobject and prefab which gets instantiated. However the problem is that the player doesn't turn blue like I want him to when he gets hit for a period of 5 seconds and afterwards he's supposed to return to normal. The slowed movement doesn't work either ever since I changed the blueballcollision script from being on the player instead of the ball. Any ideas? https://gdl.space/ubasenedom.cpp
if this is UI I suggest you ask in #📲┃ui-ux
otherwise in #💻┃unity-talk
doesnt seem code related
which one of the logs are printing ?
I am actually not using UI 🙂 , its simply rigidbodies with box colliders, that are laying on another box.
And the reason they can overlap each other is because I turned of the Physics for those layers (they can't collide with each other).
Hm but maybe you are right, I can try asking in Advanced.
Only blueball hit the coroutine logs don't work
wdym advanced? where is the advanced code question?
put a debug inside
if(player != null && !isHit)
make sure that thats running
Don't know to be honest, I'm just trying to figure out where to ask the question.
Maybe it is a shader question since offset is also an option to prevent Z fighting 🤔
#💻┃unity-talk
and if they are sprites then the Z position / X rotation matters too
Nope that if statement is not running
I need to debug.log more often looks like
alr so we know its not the coroutine
yes logs are very important , better is the debugger but logs help as well
It might be possible if something like something eeeehhhh
isTrigger is checked for the ball gameobject tho
if Debug.Log("Blue ball hit!"); is printing
its not the trigger
either player is null
Ah thanks, I'll give unity-talk a shot.
I'll consider this in the future, as of now there are no sprites, but will be once the base is established.
ah
is possible to make a video
you have to check which line
expand ur errors
what is that
Oh damn it
make a video of the issue you're having?
I want to learn coding all by myself, I don't want to watch YouTube tutorials or stuff, is there anyways I can learn C# that will make me enough to make indie games, at least like Flappy Bird without YouTube tutorials?
if you truly want to learn code and no bs attached use the Microsoft tutorials on c#
Unity is just an API
But I just want to get to the game development, this tutorial teach me everything about C#, I just wanna learn enough for Unity, C# without Unity is confusing.
if you can learn how to read API you can use any program with c#
there is no Unity c#
its an API for the engine which is written in c++
if you have c# knowledge this comes with ease, you jus need to learn what each function does
Ohh, the thing is I learnt English so easily, I just wish C# were easy to learn too, it's a language after all.
so you didn't learn English in a day right?
it ranges from easy stuff and then progresses into harder stuff
easy stuff : what are variables? what are function ? what is the correct syntax
etc.
you said you know most of this stuff from other coding you did
Navarone do you know what could be causing the error I can't figure it out
whatever you collide with doesnt have PlayerController script on it
Im not sure if you can really see it here but
Yeah you're right bro, I'll try not to get bored and start playing games while learning C#, thanks, really appreciate your help man.
Wait so if I called lets say PlayerController player = collision.gameObject.GetComponent<PlayerController>(); and the rest outside of the OnTriggerEnter then it wouldn't need to be attached to the ball script
its the fact that its in the ontrigger
hm
navarone, one more question, what you think about Brackey's C# tutorial? I know it's old but I can learn from him easily.
? I think the issue is that GetComponent can return null if the script isn't on the object you collide with. You need to check if it's the right one
did you copy this script from somewhere ? I think something is wrong in it
I say it's bad. Personal opinion. Don't like his style
Why though?
Alright Navarone it turns blue once I attach the script thanks so much
just need to make it slow now
Teaches a lot of bad habits
well no shi
his c# tutorials are the worst
that's why im here
Damn, well okay.
yeah that's the issue
Use TryGetComponent in an if statement, of do a null check
Send script again sorry, its too far up I cant find it
im bad with rotations tho maybe someone else will chime
lol
what's the best way to make scripts be able to access data for different guns like their fire rate, recoil, name and stuff?
Manager pattern
what is that?
sorry I think its called Mediator
ty
what kind of camera do you want to make?
ehm, what do you mean
Off to a good start I guess.
What type of game ? / camera do you want
Five nights?
ye
Navarone this completely fixed everything I just want to make sure I understood correctly tho. Does this instead get the PlayerController of the object which this script is attached to while the commented line got the PlayerController of the collision gameobject which didn't exist?
Yeah I think that's it actually
this looks for the PlayerController attached to this object
np. but you better off just putting a field in the inspector next time whenever you need a component on the same object as script
I thought you were looking for PlayerController on the other object since this one was named Ball or w/e lol
Yeah that would be easier lmfao
But sometimes I'm scared to do that because my prefabs were referencing incorrectly
last project
yeah my namings can be shit as well
would this work ?
https://youtu.be/VCXStm34Ft8?t=373
Learn how to recreate the FNAF camera movement.
For those who just want the script, please leave a like and download it, sound like a fair exchange? XD
Here you go: http://pastebin.com/KgzhLjvQ
The game is nearly done, I will post it the moment it has been finished.
when you use prefabs you can't reference scene objects unless that prefab is already part of the scene
Yes that was the mistake I made it confused me badly
I need to ask more often here because the way you guys deduce the solution is great
teaches a ton
repetition is the key
navarone, I do think why am I doing this, is this even useful in game dev??
definitely useful yes
of course
its useful to know the basics, if you dont know the basics you wont be able to do anything advanced
Umm okay.
its always a slow burn in the beginning and may feel like a chore maybe
I'm asking cuz in game dev, we play with Physics, Rigidbody and all that stuff, not this.
you also use this stuff alot
and it can help debug the physics rigidbody and all that
hm, well I agree.
Rigidbody is part of physics but In Unity at least, its a component smart people already made for you to use without knowing anything about coding physics
Oh, thanks.
Well I know some Python and C# is kinda same, so...
not really the same
Numbers are 
a few days ago i had my important variables showing as textmesh pro on my games gui. it would work instantly, all the variables would be set on start and the game would immediately show the corresponding figures (eg 5% crit) on launch on the screen. however now this doesnt happen and I dont know what i've done wrong. for the record, the only one that works is "timePassed" because its also sitting in the **update **bit of the script, but I dont know what is best practise here, having all of these variables just continuously updated via the Update (method?)
because you're printing c twice
oh nvm
If you want them to update, they must be in update. Start only runs once in the lifetime, and setting text will only set it to the CURRENT value of the variable
For things like max jump, start should be fine, right? Unless that changes
max jump changes but my issue here is that even on start it doesnt update the values
Current health, though, will never update in start
What do you mean update? Like it never sets ANY value?
yeah so as you can see in the first pic, private void start, i set the critchance, max health and current health, and up until about yesterday when i launched the game it would instantly show those variables
now when i launch it doesnt for some reason
the only thing thats updating is timepassed because its in UPDATE
Um I have no idea what is this, can someone help me?
Did it divide d by a and gave me the reminder?
idk, probably erased my existence.
Modulo (%) returns the remainder AFTER dividing
% is literally called the remainder operator in C#
it returns the remainder of the division operation
that's all
which is an important distinction
-1 mod 5 is 4; -1 rem 5 is -1
where's my damn modulo operator, Microsoft
Is there anything else that references those texts?
within the same script:
whats wierd is the crit chance one seems to completely omiss the first 5% crit i give the player inherently, so when i get the power up, rather than going from 5% to 15% (10% inc as intended), it goes from 0% to 10%
this was working up until like today
Stupid question - have you tried putting Debug.Log in here and making sure this code is actually running?
And checked that there are no errors in the console?
yes, you should always reach for that when things aren't adding up
"is this code even running?"
best way to do this? Debug.Log( maxHealth = 50;) or?
🤔
Without the = 50
How about Debug.Log("Hello this code is running");
debug.log(maxHealth)
printing data will be helpful but that's the next step
bonus points
Debug.Log("Hi", gameObject);
assuming this is in a MonoBehaviour
clicking that log will take you to the game object
It's using start, so hopefully haha. But that WOULD explain things
ok this helped a lot! turns out the first line of code has something wrong with it so the rest of the code wont work.
i did not know that woab
thank you
i thought i had done something stupid somewhere as all the variables etc were working yday
Now that you say that. It DOES look like your !ide is not configured
Not sure though
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
while I am here
can I check if a specific point in space is intersecting geometry
like a raycast but checking a single point
i think its setup fine dw
the best I know of is a small-radius sphere overlap query
works, i suppose
yep if you have an exception/error being thrown the rest of the code will not run
like Physics.CheckSphere(randomPoint, 0,_layerMask);?
I don't think 0 would work. But try it an see
overlap is better because it gives you specific colliders as results
thank you everyone for ur help!
i don't see like, an out hit
see the return type from Overlap
it's better if you need the colliders
but you may not
I used to use Overlap queries to check if the ceiling was too low
but that's a clear case for a Check query
just need to know if the point in space has any solid colission (doing a sort of scanner effect)
I usually use checks if i need to know if a spawn is blocked by anything solid, doesn't matter which
then checksphere is fine yea
sorry not quite sure how to do this haha
if you just care if something exists there, you don't care about the colliders you hit
you already know what the position is (it's randomPoint)
Do you want a point on the surface of a collider?
OverlapSphere would not be appropriate. You would need a raycast.
(or some other cast)
oh so if h.Length > 0 then something IS there
Correct.
or you can just use CheckSphere, which returns a bool
that's even realer
hang on the cat just came in and is screaming
he does this constantly
sorry I just remembered, I wanted to check if (hit.collider.CompareTag(REJECT_LAYER_NAME)) continue;
there’s a method to get the closest point on a collider to a given point in space
Can you not just move the object to another layer?
so I guess I should use OverlapSphere
.ClosestPoint
If not, then you'll need to iterate over all of the colliders and check their tags
Which, with such a small size, will probably be only one at least
But annoying boilerplate needed
oh, you need to know if a given point in space has any collision with anything?
are u in 2D or 3D?
3D
and thus we come full circle :p
Check a sphere centered at the point in space, and the radius is the contact length that your physics system checks
layer mask to only look for relevant things
up to no good i think
i’m just going back to the initial question to figure out wtf he wants to do
(it worked)
the answer: idk what they want to do (ourple freestyle)
i would definitely not loop through all colliders in the world. I think that will be slow as shit because of the complexity
*full sphere
and your solution would be?
well, using Physics.OverlapSphere
i don't think anyone was suggesting to just iterate over every collider
you mean like this?
and wtf do you think that actually does?
over all of the colliders that were hit
🤷♂️
without being able to dig into the source code, I have no idea how unity’s physics system doesn’t normally have colliders^2 time
this is just damn stupid, Unity are bound by the same rules as the rest of us, there is no magic, you want to find something you loop over all available object. end of line
unity can keep things under the hood that we don’t know about
physics systems use a spatial data structure to store and query colliders
like, during physics calculation, it could realistically separate things to avoid calculations between colliders that are too far
hence these settings
rubbish, if you think that you know nothing about computer systems
i don’t think you understand
without being able to see the source code, we can’t know wtf unity is up to
we don’t know its implementation
we don’t know how it is optimized
we don’t know how shit is stored
this is a multi-level miscommunication about my remark about iterating over colliders returned by a physics query
of course we can, the fact that you cannot does not mean that we who know what we are doing cannot
you can do experiments to discern, but you need source code to really see what it is doing, or need a good enough explanation of it, which I do not see
Look what you've done!
https://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/guide/Manual/SceneQueries.html
Broadly speaking, each query traverses a culling structure containing the scene objects, performs a precise test using the GeometryQuery functions (see Geometry Queries), and accumulates the results. Filtering may occur before or after precise testing.
it's more performant than iterating over every collider.
this is a given. it would be ridiculous if it wasn't the case.
you are a rank amateur, come back in 5 years or so
for example, when I tried to see what 2D effectors actually do (and how they work), I just hit a brick wall. Code is injected from closed off C++. The most I could get are a few snippets from forum posts
steve moment!
got blocked lmao
I do not think we can extract any more value from this topic.
Log in, see this, made my evening
I can't drag this prefabs transform into my scriptable objects transform fields, anyone know why?
you can't reference the inner contents of a prefab like that
You can only reference the asset itself (so, the top-level object in the hierarchy)
it looks like the query is operating on something like a tree or heap, with the details unknown
to avoid N^2 complexity
so more like N log N, which is much nicer
I would suggest putting these fields onto a component on the root of the prefab, and then reading them as needed
Pretty stupid question - how do you make grounded checks for character controller or gravity.
The problem is, on the "corner" on the collider it lays on the edge of the ramp. so the raycast detect it is grounded. but it does not slide down.
Here is the code:
private void CheckIfCharacterIsGrounded()
{
// Check if the character is grounded.
IsGrounded = Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, groundCheckDistance);
}
private void ApplyGravity()
{
// Apply gravity to the character controller if it is not grounded.
if (IsGrounded)
{
return;
}
characterController.Move(gravity * Time.deltaTime * Vector3.down);
}
private void SetSlopeSlideVelocity()
{
// Check if the character is on a slope and apply sliding velocity if necessary.
if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, 5))
{
// Calculate the slope angle.
float slopeAngle = Vector3.Angle(hit.normal, Vector3.up);
if (slopeAngle >= characterController.slopeLimit)
{
// The character is sliding on a slope.
IsSliding = true;
// Calculate the slide direction based on the slope normal.
Vector3 slideDirection = Vector3.ProjectOnPlane(transform.position - hit.point, hit.normal).normalized;
// Apply the slide velocity to the character controller.
characterController.Move(slopeSlideSpeed * Time.deltaTime * slideDirection);
}
else
{
// The character is not sliding.
IsSliding = false;
}
}
Now that I think about it, it would be nice if you could do that...
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hmm, well here's what I'm trying to do:
ItemData will hold all information pertaining to a type of item. If the item can be equipped, there is equipment mapping data to map the different parts of the equipment to different parts of the player/character model
When I create a physical prefab with this item data, I want the data to have references to all the correct parts of the equipment, but I'm having a hard time figuring out how I do that
prefab children feel like they should be roughly as "first class" as the prefab parent
I have like 3 different ways to check for ground
ooooooo
So now the prefab has a component that tells you all about it
Yeah that makes sense, I'll try doing that
You can reference that component just fine
the main way I check ground on the player (because for player it’s really fucking important) is to cast down every frame a fixed distance
expensive, but for just one guy it’s fine
Actually that's what I had originally, but I wanted to have all item data including the mapping contained in item data itself
But I suppose this doesn't exactly qualify as item data, it qualifies as item prefab data, so It makes most sense to put that under the prefab
where is mr plants?
Yeah. I think it makes more sense to be on the item prefab.
So I'll continue on with this
I guess your litmus test is "if I replace the prefab, do I have to replace every single one of these fields?"
if so, move the fields onto the prefab
well that is what i do
another way to check for ground is OnCollisionEnter/Stay. But this information is basically always 1 frame old, so it should only really supplement other information
Thank you, that makes so much sense
that is sadly not possible because it is still OnCollisionStay with the ramp
So for things like "Armor value", that test fails: you might have various qualities of armor with the same model
so it is just that "corner" case - word joke
my player uses OnCollisionEnter/Stay. I use this to check for specific types of ground (ie ice, jumpable ground, spikes, etc). Then the next fixed update, if I am not grounded (and should not disconnect due to a jump request etc), then cast my collider down a fixed distance
do NOT use a square box to check for ground. Some people do that. It will get you in trouble with edges and corners
raycasts also struggle with checking the whole bottom
it is not - like in the picutre
i’m just saying some people do
do you have friction?
so it gets basically stuck on the edge
hey, So I have a parent and 3 children. the 3rd child is a trigger. How can I use the onTriggerEnter method with one of the child GameObject colliders?
good question
in that situation, should he be on ground, or should he be falling
if the parent object has a Rigidbody, then it will receive collision messages from child colliders
shoud fall down to the ground
if he SHOULD be falling, you probably have a friction issue
You can also add a component to the child that receives the collision message, then calls a method on something else.
For example, I use this anywhere I need to sense an entity:
using UnityEngine;
public class EntitySensor : MonoBehaviour
{
public Entity owner;
void OnTriggerStay(Collider other)
{
if (other.gameObject.layer == LayerMasks.entityLayer)
if (other.TryGetComponent(out Entity entity))
if (entity != owner)
OnHit?.Invoke(entity);
}
public event System.Action<Entity> OnHit;
}
i don’t use capsule colliders because I do 2D. I use box colliders with an edge radius.
so if you fall, I can make it look convincing
LayerMasks.entityLayer is just a precomputed mask for the entity layer; it's equivalent to LayerMask.GetMask("Entity")
No ridget bodies
thanks a lot - i think i know now what do to
mr plants: first thing; make sure you set the player’s material to something with no friction
sure. Also remember you may need platform effectors for your world. Just something to keep in mind
also removing friction may make your slopes wacky, depending on if you have dynamic/kinematic RB for character controller
gotcha. idk if friction affects that
character controller is like a weird mix of dynamic and kinematic
for 3D, there is a common kinematic character controller package you might be interested in. If you forsee having a lot more issues in future, it might be worth swapping now
this looks like a GroundCheck issue
ie your collider is bigger than your ground check
thats not the case - it is just when i am on a vertices on a collider
enable the gizmos when you get stuck, screenshot it
this aint gizmos
i know wrong image 😄
what kind of ground check do you have on this
also your Mesh has 0 to do with collisions / grounding
its based on collider
private void CheckIfCharacterIsGrounded()
{
// Check if the character is grounded.
IsGrounded = Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, groundCheckDistance);
}
there you go
one single line shooting down
according to the raycast ur mid-air
and its causing animator to set to not grounded
but that is not the problem
if you say so
so you're not talking about that it switches to not-grounded ?
even with adding gravity
private void ApplyGravity()
{
// Apply gravity to the character controller if it is not grounded.
if (IsGrounded)
{
return;
}
characterController.Move(gravity * Time.deltaTime * Vector3.down);
}
private void SetSlopeSlideVelocity()
{
// Check if the character is on a slope and apply sliding velocity if necessary.
if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, 5))
{
// Calculate the slope angle.
float slopeAngle = Vector3.Angle(hit.normal, Vector3.up);
if (slopeAngle >= characterController.slopeLimit)
{
// The character is sliding on a slope.
IsSliding = true;
// Calculate the slide direction based on the slope normal.
Vector3 slideDirection = Vector3.ProjectOnPlane(transform.position - hit.point, hit.normal).normalized;
// Apply the slide velocity to the character controller.
characterController.Move(slopeSlideSpeed * Time.deltaTime * slideDirection);
}
else
{
// The character is not sliding.
IsSliding = false;
}
}
and thinks ur mid-air
nah that is fine - it is the getting stuck on the vertice of the collider - because i have no friction
I think he wants to slip of the ledge in that situation idk
ur still checking for wrong spot for slope
but you're technically not on a slope
tho idk how to do that without bunch of complexity lmfao
simple, switch the raycast to be an overlap
then you can better determine you're on a slope when on corner
did removing friction fix the sticking issue?
private void ApplyGravity()
{
// Apply gravity to the character controller if it is not grounded.
if (IsGrounded)
{
return;
}
characterController.Move(gravity * Time.deltaTime * Vector3.down);
}
alternatively platform effectors, which have a mode to remove side frictkon
ah i see what you mean
I think it's enough for today, I mean better than playing 8 hours a day, isn't it?
uhhhh
how am I supposed to debug random lag spikes
Profiler
Profiler
Profiler?
Profiler.
Profiler.
Profiler.
Profiler!
stats is okay for looking at tris, batches and quick stuff like that, but usually not accurate for spikes
The timeline shows what methods ran in what order
Children appear below their parents
So, you are spending 14.14ms per frame in SoundOrbLogic.FixedUpdate
these are probably individual queries
I presume this is because you're doing all those OverlapSphere queries
This will be useful for you.
It lets you perform a very large number of queries in one big go
Even if you don't manage to get any parallelism out of it, you'll still be saving time compared to doing many individual queries
The ideal scenario would be to start it early in the frame, then read it later in the frame (or even in the next frame)
note that physics commands are forcibly completed before the physics world gets messed with
I couldn't get RaycastCommands to run between two frames because of that, for example
But I still got a significant boost
this is some arcane shit
i made some improvements actually
simply increasing the inital radius spread, decreasing points, reducing points as range increases and making the scan more coarse did wonders
You can also make the updates less frequent
did that too
Reducing points as range increases will be a big help.
reduced scans per frame
You can also cull points you can't see
(strictly based on view direction)
not even thinking about occlusion culling here
you COULD also bake occlusion culling, and then...not quite sure what I'd do with that information, actually
I think you can ask "is this thing visible?"
but I've done very little with occlusion culling
will ponder this!
Really new to unity, trad dev playing around with game dev for fun.
Trying to get a grasp of rendering/meshes/colliding/etc
Imported a random env and trying to figure out the ground prefabs
For some reason it renders in scene but when i hit play, my player controller falls on the "Concrete" (if i move in either direction a bit i fall) however i can't actually see it when i look down, it's invisible. What am i doing wrong?
is it still invisible if you disable the LOD Group component?
that's my first suspicion
Also, to sanity check: add a new cube (GameObject > 3D > Cube). Can you see the cube?
If you can't see the cube in the Game view, then your camera is messed up
So im having a silly little problem with Behavior Designer where transitioning from one of its built in nav mesh nodes to my own the character just freezes. The node still runs, and properly updates the agent destination, but it just stis there. No errors or anything
Ive been looking to see if their scripts change any agent settings that could screw with the movement, but I'm kind of at a loss for this one.
heres my code if that helps at all https://hatebin.com/ybkdukamff
im trying to code (ish) im making a simple game any ideao why this isnt working im sure its an easy fix but alas
It seems to be getting jammed when it starts pathing towards you
Ah, right, that's the transition.
Are you setting the destination every frame? I've seen problems where you never get a path if it doesn't actually manage to finish finding a path before you ask it to change destination again
But that shouldn't really be a problem for such a direct path (I saw that when asking for an unreachable destination)
Did you mean to write = instead of * ?
= makes no sense there
this tries to assign 10 into Vector2.up
(the second one)
oml your right my im blind i guess thank you
You should check if updatePosition is true
But, nah, if that was false, you'd see the agent cylinder moving towards the player, leaving the model behind
so that isn't going to be the issue
maybe isStopped is becoming true?
ill check
for this, do I batch the calls and then just loop through the results? go through the resulting array and write the points to my shader graph?
You would be gathering up all of the points to check, then running the command
afterward, you'd tell the points whether or not they hit anything
oh, so make a big list of the random points, run them through the command, and it outputs only the ones that hit?
it'd make sense that it stops when exiting the state
so that it doesn't keep moving
although I usually just set the destination to the current position to do that
close enough
thank you for the help
np!
fen i think a lot of people really appreciate how much time you spend just helping newbies
Hey how do I reference a public void function from another script?
I tried script.publicvoidfunction(): but it didn’t work
If I want to make a glowy transparent circle. What is the best tool for that?
This did not help
should I be using the particle effects package
are you referencing the instance or the class?
The script
So class
(In the script)
public void lala()
{
}
In other script, script.lala();
public class MyClass {
public void MyFunction() {}
}
I cannot call MyClass.MyFunction(). But I CAN call:
MyClass instance;
instance.MyFunction();
Why would you include public or void in the reference?
Just DON'T include those words
Public is a scope modifier, and void is the return value
Well, i'm confused, THIS code IS how you do it. (As long as script is an instance of the class)
I’m trying to use the public void from another script in the one I want to call the function in
Public and void are irrelevant here
Ignore that. Just use the name.
do they share a namespace?
did you read my comment?
Oh I didn’t see it
you could show the code if you still have issues, so we can give more concrete suggestions.
But in essence, after declaring the class, you don't use public or void
Tried it, but it said
“Use of unassigned local variable ‘instance’”
You have to CREATE the variable
It isn't implicit
That was just an example they showed
yeah, the instance isn't initialized
This is going to help the most. It shows EVERYTHING you could possibly need to know about this
#💻┃code-beginner message
.
Yeah, that is incorrect. It will help. No offense.
If it doesn't explain what part is confusing. We can help more
think of it this way. The class defines a circle, and you wrote a function to get the area. You cannot get the area of the idea of a circle, because that's not actually a circle. But once you have a specific circle, you can ask to get its area
There are a lot of links to follow. You need to spend time on it
But like I said, show actual code
Then read it again until it does because this is everything you need to know
if I make a circle of radius 2 at (3,5), then I can call thatCircle.GetArea(), and it should give me 4pi.
but I can also have a separate circle of radius 1 at (6,9).
I need to have a reference to the specific circle whose area I want
does this make sense?
Im still a bit confused. Just in case I confused any of you, im wantting to call this from the script to here in another script. I looked at the page again but im still confused
Reference the instance you want to call the function on
private float radius;
// This is a constructor to make a new circle
public Circle(float newRadius) {
radius = newRadius;
}
// Get the area of a SPECIFIC circle
public float GetArea() { return 3.14 * radius;}
}```
then in other code, I could do something like:
```Circle circleOne = new Circle(5f);
Circle circleTwo = new Circle(1f);
Debug.Log("Circle #1 has an area of 25pi: " + circleOne.GetArea());
Debug.Log("And circle #2 has an area of pi: " + circleTwo.GetArea());```
the character show one?
Which object do you want to call the function on
You should read my comment, fishy
That link shows all the ways to reference a script. I promise you, it is very helpful. If you can, you want a serialized reference (drag and drop)
We can't really help without more info though
Do both scripts exist in the scene before play? Are either instantiated?
gameObject, I just need it to function
the current one
So both scripts are on the same object?
If so, use GetComponent<ScriptName>()
GameObject doesn't have that function you showed
What object do you want to call that function on
@sly wasp do you understand how this code works
A class needs to be tied to an object for methods to be called on it. When you are calling a method you can't refrence the class, you must refrence an object derived from that class.
In plain c#;
you can make your class:
//vars
public void doLemonStuff(){
}
}```
Create an object from that class
```public class program{
public static void Main(string[]args){ -- ignore these few lines, they are just there to show that this is in a new class that is running code.
public Lemon myLemon = new Lemon(); -- The class must be made into an object before its methods can be used just like this
myLemon.doLemonStuff() -- Now I can do lemon stuff
}
}```
it would be myLemon.doLemonStuff();
this isnt exactly what it looks like in unity, but this is to give you an idea of why you cant just call Lemon.doLemonStuff()
yeah I was distracted trying to write two things at once lol
unless it's a static method
yup, i decided to not mention that to reduce confusion, but you certainly can
and that could be a solution to the problem depending on what their particular script does, but that hasnt been disclosed
Either way, the best explanation would be presented in a book/course when learning C#
Not when trying to do something in Unity with little C# knowledge
yeah, thats one thing that a lot of people stuggle to comprehend when going into this is that you need to know c#
at least the basics
Or use Unreal and blueprints 
am i allowed to ask about code unrelated to unity (for example C# console application in VS)?
!cdisc more relevant
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
thank you
How do you work with the input system presented in the FirstPersonCore template from Unity 2021? I'm struggling to figure out how to use it. I'm trying to make a basic weapon
StarterAssets.GunController.MainInteraction () (at Assets/Scripts/GunInfo/GunController.cs:23)
StarterAssets.GunController.Update () (at Assets/Scripts/GunInfo/GunController.cs:19)```
this seems like a simple error, but how exactly do you fix this?
```cs
using UnityEngine;
#if ENABLE_INPUT_SYSTEM && STARTER_ASSETS_PACKAGES_CHECKED
using UnityEngine.InputSystem;
#endif
namespace StarterAssets {
[RequireComponent(typeof(AudioSource))]
#if ENABLE_INPUT_SYSTEM && STARTER_ASSETS_PACKAGES_CHECKED
[RequireComponent(typeof(PlayerInput))]
#endif
public class GunController : MonoBehaviour {
public AudioSource gunSound;
private StarterAssetsInputs _input;
private void Start() {
}
private void Update() {
MainInteraction();
}
private void MainInteraction() {
if (!_input.mainInteraction) { //error line
return;
}
gunSound.PlayScheduled(0);
Debug.Log("Gun shoot");
}
}
}```
I would turn IntelliCode off entirely
Visual Studio IntelliCode is an experimental set of AI-assisted development capabilities for next-generation developer productivity.
it mostly just suggests useless names
I am surprised that [SerializeField] can be applied to a method at all
I guess it doesn't declare any restrictions
so you can stick it on whatever you want
attributes don't do anything by themselves
would be lit if text box appears in editor
and u can type into it like notepad or smthn

quick question: why does doing musicSource.clip = Resources.Load<AudioClip>(songPath); not work while musicSource.clip = Resources.Load<AudioClip>("Songs/testsong"); does??? even though songPath is literally the same as Songs/testsong?
not exactly the same but vierually the same
then songPath doesn't contain what you think it does
is this the correct component? is there more than one copy of it in the scene?
also, ensure that there isn't a space at the end or anything like that
And ensure you don't overwrite that variable anywhere in code
you can prove that it's got the right value by logging the value of songPath before using it
omg it was the newline character 🤦
thank you this fixed it
I am trying to load a scene in additive mode but it looks like that async load never gets to the isDone state.
`AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(scene, LoadSceneMode.Additive);
// Wait until the asynchronous scene fully loads
while (!asyncLoad.isDone)
{
print("loading");
yield return new WaitForSeconds(10f);
}
print("loaded");`
Am I missing something with scene loading?
oh, wait, I'm unloading the previous scene, which probably dumps the coroutine
I think u can just do yield return new WaitUntil(() => asyncLoad.isDone); inside coroutine
I wanted the text so I could see how long it was spending loading
that would still die if the MonoBehaviour your coroutine was running on got destroyed
ya my problem is that my scene switcher was getting culled
you could do this in a DontDestroyOnLoad'd object so that it's never unloaded
when scene is gonna load in one lol
to each their own. for me it was equally as helpful as something printing every 1 second.
I just wanted to know if it was still in the while loop or something downstream
yanno?
anyway problem solved, scene switcher moved to the meta scene that I didn't want to unload (hence the additive scene load and manual unload)
thanks!
u print and start 10 seconds wait just put that print before WaitUntil I sent and its the same thing
using WaitUntil would not let you print messages on an interval
(coroutines don't just run "in the void"; they're attached to a specific MonoBehaviour)
that's where the StartCoroutine method comes from in the first place -- it's a member of MonoBehaviour (rather than being a static method or something)
hes not printing it in intervals well the code does that but its not gonna print again scene will be loaded ages ago
ya, TIL - I guess I had assumed they were jettisoned off into their own space before they cleaned themselves up. funky stuff!
Deactivating a MonoBehaviour's game object also kills all of its coroutines.
Bump 🥲
have you looked at other code that uses StarterAssetsInputs ?
You will need to do something to give _input a value.
Ye, i pretty much copied it from FirstPersonController.cs
It's going to be null by default
It just leaves _input like that
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Yessir. Give me a sec
is there any way i can modify a single direction of a vector3 without doing the following?
whatevervalue = new Vector3(ogvector.x, 0, ogvector.y);
Use the current vector value's x/y/z as one of the new vector parameters
can you give an example please?
Vector3 newVector = new Vector(oldVector.x, oldVector.y, oldVector.z);
Replace any of those three with the new value you want
yeah thats what ive been doing, im wondering if theres a faster way or a shorthand or smth
You could do, like:
Vector3 oldVector = transform.position;
Then do what I wrote above
Not afaik. Probably though
hmm alr, thanks
I do realize I misread your first question though. Sorry about that lol
👍
Vector3.ProjectOnPlane(ogvector, Vector3.up) is equivalent.
Not too much nicer.
It does let you "zero out" any direction, not just a cardinal one, though!
ah, that shoul be of some use- thanks!
public static Vector3 ChangeX(Vector3 v, float x) => new(x, v.y, v.z) lol then maybe u can do transform.position = ChangeX(transform.position, 50);
so you might do
Vector3 horizMove = Vector3.ProjectOnPlane(velocity, gravityVector);
that would give you the velocity perpendicular to gravityVector
useful for something like Super Mario Galaxy
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
see line 94
_input = GetComponent<StarterAssetsInputs>();
StartedAssetsInputs is a component you need to attach.
gahh. thanks
doesn't anyone have a video tutorial in which I teach you how to create objects on fire in rigidbodies?
how do i turn VS code trust mode on all the time? every time i open a script it opens and says that its in restricted mode. I dont want that. I never want that. every time i open a file I set it to trust mode. even if i open a file ive set it to trust before it still opens in restricted mode. how do i stop this?
what does "on fire in rigidbodies" mean?
It means that the fire moves in the position of the object when it is moved (be careful, it does not change its rotation when the object rotates)
why isnt this working? its the lego microgame
make the fire a child of the object?
his rotation isnt relative to his gameobject
yeah thats easy
but the particle instantiate is difficult
well, is the Touch Trigger placed on a brick?
sounds like you're opening a completely new window each time?
go to File -> Open Folder, then navigate to your project directory
(not the Assets folder -- the folder your entire project is in, one level up from Assets)
I think
open folder where?
ok nothing shows up when i do that
clicking "Open Folder" will bring up the file picker
i am unclear what "nothing shows up" means
do you mean no files are open?
that is expected.
i mean like no files show up at all
it will only display folders
you are in some random folder (probably in your project)
navigate to the root directory of your project and select that.
ok
ok so i did that and when it reloaded it asked if i trust the authors of the files i hit yes
now double click a script asset
also, if you have not already done this, you should set up your code editor
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
follow the instructions for VS Code.
that did nothing my vsc still doesnt suggest code and stuff
oh wait hold on this just appaeared
here is the code but its doesnt works for me 😦 if (isInFire) { particleInstance = Instantiate(fireParticles, transform.position, Quaternion.identity, transform); var v = particleInstance.GetComponent<DestroyInRandomTime>(); if (!v.isActiveAndEnabled) { hitsReceived = maximalHitsToDestroy; } }
what about it doesn't work
Did you follow all of the instructions without skipping a single line?
ok so about this thing, I downloaded it and it still appeared and then went to the help button and did all the steps there but it still doesnt work
yes
I have a problem with this code
'GUIText' is deprecated: 'GUIText has been removed. Use UI.Text instead.'
how should you handle input contexts? like say a player equips a weapon, and now the context changes
this is pretty simple issue, so i'll ask here
i want to spawn a bunch of Shruiken particles at specific points, just for temporary visuals (they fade quickly.) is the best way to do this seriously to move a an empty Gameobject with a ParticleSystem attatched to each point, burst 1 particle, and then move it again until it's spawned particles at every single point?
what do u want to reference
Do you ask me?
yea
State machines..? Really depends on the specific case and your project structure.
What is the issue? Change it to Text, as it says in the error
Unless you're using Text Mesh Pro
I mean in the scene
tho yeah bet my balls u wanted TextMeshProUGUI here but idk where u got GUIText from
I wanted to make a car controller but I get this and I downloaded it in the asset store
yea thats what I do have particle system with 0 emission rate just sitting and controller moves it around and emits itself you dont need to instantiate/enable or let particles die off before destroying/disabling either
Did you check when it was made
Ok.. the asset is old then. But again, show the inspector of the object with the text component
is this not a big performance hit? i'm trying to save as many cycles as i can here haha
its as cheap as u can get prolly
will give it a shot :)
im making a flashlight for my game and I have an issue where its automatically toggled when I start the game. I have it untoggled in the unity editor and Im not sure why its turning on automatically?
welp,if its set isInFire on true the particle doesnt spawn
What is passing the file name is fine and it won't let me put the script where I want it.
Do you have compile errors?
no
What's the filename?
prove it by showing us a screenshot of the entire console
Yeah I'd guess you have compile errors then
GUIText is extremely old
I've never even heard of it
If you do not have a very good reason to not use TextMeshPro, you should use TextMeshPro.
and what do I put
using TMPro; up top. TMP_Text for the type
You ducked out on us when we were trying to fix that earlier. I knew that was gonna be the issue
For future reference, those red exclamations are compile errors, and should ALWAYS be handled before moving on
I attach InputActionReference components to the things you can control. I subscribe to and unsubscribe from performed events on actions to turn input on and off.
I didn't abandon them I went for water xd
Fair, but rather than continue when you came back, you brought up another issue.
I'm just letting you know that if you have a compile error, you gotta fix it befor moving on
No worries though. Just a learning opportunity
And what do I have to do to solve that?
You should show the object in the scene like we kept asking, or just do that 👆 and hope that's the right type. Tmpro is what you SHOULD use, but maybe you used legacy?
I have a very stupid question to ask but i just dont understand. Why is the Pos Y of a rectTransform in my inspect different to the position when I run the game? I have tried localPosition and just Position but still doesnt come out right.
It's anchoredPosition
@young warren yes thanks I knew it was going to be something simple
YES YES YES YES YES!!!!!
I'll take that to mean it worked haha. Nice
the weird conclusion to this saga
the performance would degrade, then improve, then degrade in a weird loop
i figured out after some experimentation that the issue was actually that my shader reading a texture2d was making the texture2d WAY too big
thus making the write calls in SoundOrbLogic extremely slow
look go to the channel where they show the progress of the projects
and when it generated a new VisualEffect object the lag stopped
i simply turned down the size of the Texture2D and voila
How can I make the R joystick control the car so that it goes left and right?
and that the LB and RB buttons go forward and backward and that the A button makes it brake
is there a place where I can specifically see what would cause RaycastHit.triangleIndex to return -1?
Help.
I created a new scene and double clicked it
now everything is gone
how do I go back to where everything is?
Just click on the other scene in your assets
there isn't any
Then click on Start Screen
start screen is what you're seeing right now
is the collider you're hitting convex?
Okay so do you at least know what the scene that you need is called?
i believe so, lmc
no
I dont think I've made a scene in the beginning
YOOOO
Welp I don't know how to help you then, just try searching for other scenes with the unity icon
Good for you
theres some chrome extension, i believe from vertx, that lets people comment on undocumented behaviour.
https://docs.unity3d.com/ScriptReference/RaycastHit-triangleIndex.html
and vertx commented this under the docs
oh shit, thanks
sorry, could explain again what this is?
A browser extension that adds a comment section to documentation
oh wow, thats awesome, thanks so much
thanks for telling me about it too @eternal needle
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hello, I want my game object to randomly change it's position within a certain radius from it's initial position. How do i start to do that?
so like, if I have non convex mesh colliders then do I need to add a kinematic rigidbody to each mesh? And also, can you have multiple rigidbodies in one prefab?
https://docs.unity3d.com/ScriptReference/Random-insideUnitCircle.html
you can use this to generate a random point, then scale it by your radius
right now, the prefab for my player would have to have a non-kinematic rigidbody with the hitbox collider, and then a bunch of children mesh colliders each containing their own kinematic rigidbody. Is this ok?
ohh, I can also use rigidbody setPosition for this right?
private void MouseClick()
{
Vector2 mousePosition = mouseInput.Mouse.MousePosition.ReadValue<Vector2>();
//error Object Reference not set to instance of an Object
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector3Int gridPosition = map.WorldToCell(mousePosition);
if(map.HasTile(gridPosition))
{
destination = mousePosition;
} Does anyone know why the code here might be producing the commented error?
Is the error on the line above or below the comment?
below
You don't have a camera that's tagged as main camera
what about this error
Fix the camera first
I have a tilemap set of Terrain. Each tile is 16x16. When I put the Tiles in the Editor, they come out as blurry. How can I fix that?
i dont recall there being a .setPosition, but if there is then sure
I did
try turn off compression & set filter to none, on the spritesheet
It worked thank you
weird question, does anyone know how to rid of this box cursor, Its just annoying to use cause i cant adjust small lines between code and it deletes everything around it. this is visual studio 2022 btw
press insert on keyboard
oml ty
I want to rename a sliced Sprite. How can I do that?
in the sprite editor
Thank you
how do I check if a gameobject is within my camera view?
I created a scriptable Object that has a sprite image container.
And when I put the image in and wanted to display it on screen as a tooltip I just realized.
There is no way to link UI image or a UI rawimage to a tooltip object that recieves only sprites. UI Image is considered an image and rawimage is a rawimage so if I change the code in my Tooltip object to make it recieve rawimages or image, then I can't seem to modify my own 2D sprites into images.
I did fix this issue in the past but I forgot how to do it!
If you just need a reference to the sprite asset use the Sprite type. Or Texture/Texture2d.
did you google for this? theres a ton of solutions
My player turns red like I want him to in the IEnumerator. But he doesn't turn back to normal the Debug.Log(Timer Over!) doesn't work.
I can only assume that your code did not compile. Nothing here is suggesting an issue.
how can I change this so it doesnt keep adding until +1 each time i press interact until i pick up the battery itself? I can see my mistake just cant find a solution to fix it. (this script is on my battery itself)
Hey, is there a way I can make only the edges of my box act as a collider? ie an empty box?
How can I make the R joystick move the character and the other L joystick move the camera?
if flashlight is active and button down
if target not null
flashlight battery ++
destroy target``````cs
On collision/trigger enter
if tag is player
col get component .. player = this``````cs
On collision/trigger exit
if tag is player
col get component .. player = null```
Doesn't sound related to code, try asking in #💻┃unity-talk
Thank you for your reply. the if target not null, would the target be the battery itself?
The physics callback message gives you a reference player, consider using that reference
Just put multiple colliders on the edges and shrink them down to the size you want them to be
Not sure about your system but it would be the power up that you'd want to consume.
Am I able to post videos here?
or shall i create a thread. as i have a few questions regarding raycast
You're able to do any of the above, yes.
Raycasting
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerPhysicsController : MonoBehaviour
{
Rigidbody _rb;
[SerializeField] private float _jumpForce;
[SerializeField] private float _moveSpeed;
private bool canJump;
// Start is called before the first frame update
void Start()
{
_rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
canJump = true;
}
}
private void FixedUpdate()
{
if(canJump)
{
MoveForward();
Jump();
}
}
private void Jump()
{ if(canJump)
{
_rb.AddForce(Vector3.up * _jumpForce, ForceMode.Impulse);
canJump = false;
}
}
private void MoveForward()
{
_rb.AddForce(transform.forward * _moveSpeed);
}
}
Why does my character only move after I jump? I want it to move in a constant speed without user input.
I got a physics material with 0 friction on both the ground and on player.
Do you add force anywhere other than Jump and Move Forward? (both which are restricted by canJump in fixed update)
With your current code, no locomotion is started till jump is pressed at least once.
Ohh
my bad my bad. I forgot move forward inside canJump condition
thanks.
Add force continously adds force right? Is there any way to set it so that I start and move along with the same speed?
Add an impulse force once in Start
It would be as fast as the force you apply to it
It moves too fast even though I set my moveSpeed to .1
I am happy with the movespeed I just want it to stay consistent
well you obviously have to remove the MoveForward call from FixedUpdate too
Oh? Why? I thought physics based stuff went into fixed update
that's the part that keeps adding more speed to it
If you add force once in Start then it keeps moving at that speed if you have friction and drag at 0
Ahhh
The other option is to keep what you have and set drag instead
And the third option is to set the forward velocity manually
you mean directly setting rigidbody velocity?
yes
All right I will give it a try. Thanks!
If you've got no friction, probably consider adding force only once in Start with an impulse rather than continuously add more force.
Yes I have no friction
Just a preference question. When equipping items, do you pass in the player's reference into its equipping function, or do you assign the reference of the player immediately when picking up the item?
Can I add a component via string? Like I want to add a Stunned : Monobehaviour component to a class via "Stunned" string
Kinda odd how a lot of my stuff has no ownership binding and I only pass in the references
I have a list of component type names and i wanna add them in a GO
Yes, sort of
how 
With reflection you get the component
oh yea refleksi thingi
But reflection is bad, and especially in Unity
You should see about code generation to prevent it, or just make a dictionary
I dont mind reflection, it's just a save system thingy
Yeah do a dict
A dictionary would only work if you know the types at compile time though
That's why you're best off with code generation if you know how to do that
You trying to save status inflictions to persist on loading?
could just do IDs on them effects and apply them when you restart
I would recommend you don't save data absed on the component's name like this, if that's your goal
Just deserialize your data and have a handler set every component manually.
AYE, THANKS, IMMA GONNA DO DICTIONARY :>
.ToLower()
How can dictionary work though? I can do a switch(string) and add the component per case, but a dictionary? How?
what are the kvp to use?
Dict<string, Monobehaviour>?
I would do Component since that's the lowest type Unity methods generally accept
Actually, that's not true. You want to add the component and add the data through some sort of method I assume? Then I would suggest an interface
It really depends on the functionality
u can assume different components needs different data to save/load how does interface solve that? Just curious cause im using switch since I couldnt figure that out without making generic poco and interpreting that per component
Here is a simple code block that gives weird results... I have a 2d-grid of cells, that want to know how many neighbours they have and who they are. I thought the quickest way to test that is to disable their own collider, OverlapBoxAll at the cells position and then reenable the collider. But for some reason some cells have really overblown results (25 neighbors) event though 9 should be the possible maximum. I really have no idea why, can anybody help?
for(int i = 0; i < _Cells.Length; i++)
{
_Cells[i].EnableBoxCollider(false);
Collider2D[] colliders = Physics2D.OverlapBoxAll(_CellTransforms[i].position, Vector2.one * 1.5f, 0f);
_Cells[i].SetNeighbours(colliders);
_Cells[i].EnableBoxCollider(true);
}
(Unity2020.3.34f1)
the obvious one is ur overlap box might be too big also how can there be 9 neighbours max or result 25 your iteration cell is counted in as well prolly
also if an object has more than one collider it is possible for each of those colliders to be in the array
Each cell has only one collider, and no two cells are in one spot. The box is also not too big, as only 3 instances have ridiculous high neighbor numbers. Some cells get it right, some miss neighbors or get wrong neighbors.
well you are using a different array to get the position for your boxcast. is there a particular reason for that instead of just using the _Cells array?
The result is the same if I do _Cells[i].transform.position, I just though calling .transform performs a GetComponent<> each time so I cached them at the start.
Dumb question: OverlapBoxAll is in the xy-plane, right? Because all my cells are in xy with z = 0.
yes, 2D physics is only on the X and Y axes
also you are unlikely to see much performance benefit from caching the transforms. it's not really going to make much of a difference. but if you choose to keep using separate arrays you also need to be sure that your arrays are absolutely the same order or else you'll see issues where some cells have the wrong neighbors
Ok thanks I'll keep that in mind, but as I said it doesn't make a difference which array I get the position from.
okay and what debugging steps have you taken to ensure only the correct objects are being detected by the overlapbox?
A quick question, I have a script from the asset store that I would like to verify regarding collisions, right now I'm getting the intended results for moving left and right with it but jumping doesn't seem to properly detect grounding (and resultingly ends with a stuck pose). So I was wondering as to what I should look for to figure out what is happening.
I have checked if there are overlaps in the cells (like two cells in one position) - this is not the case. I also wrote this to check which cells are causeing problems
if(colliders.Length >= 10)
{
Debug.LogWarning("Too many neighbours");
for(int j = 0; j < colliders.Length; j++)
{
Debug.Log(colliders[j].gameObject.name + ": " + colliders[j].transform.position);
}
}
But I am have really no idea what to debug because to me it seems as if BoxOverlapAll does not produce the results it should. :/
I mean I could rewrite it to manually check all 8 neighbors with OverlapPoint but that seems to be the dumbest solution 😄
have you drawn the boxes for the overlap box to ensure they are positioned where you expect them to be?
And I dont know if that matters: All objects are instantiated, positioned, checking for neighbors etc in the same frame.
Might this cause problems?
it depends entirely on the order of operations
Ok then this should not be a problem
Ok I can do this, thanks.
also what is the actual use case for this? because it seems like you could probably just have a 2d array where each cell can just access said array to look up its neighbors on the fly
how do u draw a box is it 4 Debug.DrawLine or smthn
actually i shoulda just googled
first time I see Gizmos class lol
i personally just use vertx's debugging package so i don't have to do any of it manually and so that it is built right into the query
Unity also has physics query visualizations built in to the physics debugger now
that's 3d only though
Ah yes.
I want to do a game of life with static cells. So the game is to create the proper setup to achieve some goal that is different on each level.
yeah just use a 2d array then. no need for physics queries if this is just for game of life. don't even need colliders at all tbh
_Cells[i].SetDebugRect((Vector2)_Cells[i].transform.position - Vector2.one, Vector2.one * 2f);
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Vector3 bottomLeft = _debugRect.min;
Vector3 bottomRight = _debugRect.min + Vector2.right * _debugRect.width;
Vector3 TopLeft = _debugRect.max - Vector2.right * _debugRect.width;
Vector3 TopRight = _debugRect.max;
Gizmos.DrawLine(bottomLeft, bottomRight);
Gizmos.DrawLine(bottomRight, TopRight);
Gizmos.DrawLine(TopRight, TopLeft);
Gizmos.DrawLine(TopLeft, bottomLeft);
}
Well I kind of do because I don't want to fill a 2d-array with all slots
Each level has a unique shape made of grid - and some overlap, have holes in them etc.

