#💻┃code-beginner
1 messages · Page 722 of 1
im a dumbass mb, forgot this shitter existed already
so after all that..
and after u normalize it but before u use it to multiply w/ ur speed modifier
Instead try to understand what pro builder can do and see if you can instead modify the points of a probuilder poly shape at runtime to create a shape as you desire for your set of points.
https://docs.unity3d.com/Packages/com.unity.probuilder@6.0/api/UnityEngine.ProBuilder.PolyShape.html
If you make a poly shape in editor and see how that works I hope it will make more sense to you
after this line
editwait ... ignore what i said.. that should already be moving u the correct way
b/c ur already multiplying each axis w/ the local one...
ok sir 🫡

if this script is on the player object its working fine..
b/c in the video ur rotating the camera around the player
the players direction never changes..
if u select the character (movement script object) and watch its transform it'll show u its orientation.. thats the transform.forward and transform.right that ur multiplying the input by...
if u wanted it to move the direction ur camera is facing instead.. u'd multiply ur inputs w/ the cams direction/axis cameras.transform.forward and .right
if upsets me you rebuilt what took me 3 days

ive been working on CC's for bout 4 years now 😄
i have quite a few already in different stages.. just ready to help
well thats nice, thanks, ill try to get this working better, even if itll take the next 3 horus
i will say i was pressing w for all examples though
:(
this is what i get for trying to learn through tutorials after spending only 1 week on microsofts c# thing
CCs have alot to do with math.. (basic stuff like geometry)
knowing the Vectors.. the Directions (the relation between Local/World) magnitudes / normalization.. why we do that.. then its multiplication and addition usually
the camera / rotation work is usually a bit more complicated (still pretty easy tho)
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131 this a banger of an asset that could help u get jump-started altho i do prefer building the character controller myself (atleast what i can)
i found out whats wrong with it actually!
just messed around, seems the player is being SNAPPED and forced to face the "true north direction"
as seen by this
oh yea, thats much better example..
def messed up.. (how are you rotating?) im having a hard time figuring out how the movement and rotation is supposed to be working.. also share ur !code in case someone does know
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://paste.mod.gg/diintunuizhg/0 rotation with a script centered around the free look cam, set it up after our conversation to try to see if i could just brute force the issue ( i couldnt )
https://paste.mod.gg/vgukujkjpssj/0 my movement scripts i tried to make on my own after watching a bunch of 5-6 year old videos
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
brute force the computer to do what i want 😈
i wish it worked like that...
https://hastebin.skyra.pw/usazezezeb.csharp can someone tell me why i get an IndexOutOfRangeException on line 25?
ya, soo..is ur rotation script also trying to rotate the same object the freelook camera is controlling? to me it looks like theres some code fighting back and forth.. (the jittering)
very much so :(
i was following a video for the rotation script and its like almost 4 years old
so i really didnt know what was going on
i dont want to have to watch videos, but theres so much on the documentation, and probably a decent chunk of it ill never use, so i want to find out what i am going to use
and how to
i only made it after the fact though. my character wont stop moving in one direction
its like the character was made on a 2d game like vampire survivors, W is up, A is Left, etc. absolutes that never change.
i ant my w to send the player forward based on the position they are facing, not the camera
god this field is so hard

screw it im remaking my entire movement script again, this time around the cinemachine camera...somehow
What isn’t working
nah i fix it i get some coffee
its because i tell print the number not i tell him to print number 0 (c# is counting from 0 to ...) soo i fix it
everyone you need coffee
When you get this error in inspector, is there any way to know what script it was looking for? I tried looking through git differences, but everything is in IDs and not names
There might be info in the Metadata file. Should be the script type in addition to id somewhere
(Fixed it btw, set up a mathf and converted it to degrees, and then applied it to the camera rotation and player)
what is the difference between NavMeshAgent.NextPosition and NavMeshAgent.Destination? i see that they both output the same thing,they both set the next point where the agent goes so what is the difference?
there is also NavMeshAgent.path that can still be used to set a path
docs seem to suggest that destination is where it's trying to go and nextPosition is where it's trying to move to (to get to the destination)
why is this button not working? 🐒
using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
using UnityEngine.UI;
public class Help_Off_Button : MonoBehaviour
{
public GameObject HelpPanel;
private void Click()
{
HelpPanel.SetActive(false);
}
}
it's responding to my click (i can see it blink when i click it) but it's not doing anything
hmm perhaps because you didnt actually pick the function it should call
@rotund root ^
ohhh
you can subscribe to the event in code or do it via the UI like this (but you need to pick the function from the dropdown list)
adding to this, you can also target the gameobject you want to disable and execute set active with the checkbox set to false
no code needed then 😄
hey guys im new to unity
would anyone mind hopping in a call with me
i have some questions
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
ask questions in a channel in text instead of expecting someone to be your tutor
@grand snow @rocky canyon yesterday at 3 am i came up with a solution for my mesh problem if you remember. Forgot to tell you guys about it though as i was craving either sleep or immense amounts of coffee. What if i create a triangle fin by making a triangle with vert indexes i, i+1 and the coordinates 0,0,0? Like a triangle fin as used in circles. Obviously wont work well with to complicated shapes but after making 2 triangles before i almost passed out of tiredness It looked like it could work. I tried making a normal 3x3 grid first by making 4 imaginary points in the middle but i was afraid of it glitching when squished to much as these points werent moving with the others, rather they stay around the geometric middle with an offset. So i thought id merge those 4 center points into a single one in the center. Topology wise probably nof optimal but simple and hopefully enough to get it colored.
Im not sure if i was dreaming or if this really happened but ill look into it later today
NGL I hardly understand what you mean but an video/screenshots would help.
Triangle fans are used to produce shapes and re use of verts is always a good idea. That's why triangles are defined as vert indexes.
Perhaps consider opening a thread to continue this in #1390346827005431951
Im on my phone but ill grab a paper to explain what i mean more clear
No rush
@grand snow I hope this makes it a bit more clear. The imaginary point is stored on the last slot of the array i think that could cause a bit of confusion
So in a for loop a triangle is essentially i, i+1, imaginary point
Ah right yes that's a good plan. Make sure you generate uvs too as you generate it.
How do i do dat?
If it starts as a square then you can easily figure out the uv coordinates. Bottom left is 0,0 and top right is 1,1
Oh thats really easy actually thank you. Ill look into it in the evening
Yea with a shape like this you can easily define it. Open a thread in #1390346827005431951 to continue with this topic in future
Thread is open
hey so like how do you actually make UI bars for ints like player health, mana etc?
Don't cross post. You've been given the information you need to be able to do it - you now just need to go and learn on your own with that information.
what
I see now you deleted your other msg, so haven't crossposted... but you've been given the info you need to be able to do it.
It's also an extremely common thing, so you'll find lots of tutorials online
help me bro
You need to !ask questions to get help, here.
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
okayy
how do i actually use unity
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
like iam abiginner
alright now im really confused
https://www.codedump.xyz/csharp/aLGb_Plli_PGg5hK
it worked amazingly, but after adding the cooldown (not the timer), even after the isDashing is false, it still slowed me down until the cooldown was finished. Like the cooldown itself, which is really weird because it shouldnt affect speed at all, let me record an example of it happening
and yes, this happens even if i set the CurrentCooldown manually without dashing
if you want more specific numbers averrage speed goes from 5-6 to 2-3. If i set it so the cooldown is 0 (so ti sets the cooldown to 0 when dashing) it doesnt happen, so its somehow tied to CurrentCooldown being above 0
what exactly did you add?
the cooldown
its in the codedump
everything named cooldown
nothing else
does it work properly again if you remove it
it would be easier if you kept your code formatting consistent
its kind of a mess
so the slowdown is caused by the part that involves the DashSlowdown variable?
hey, is this aproach for stay on the plataform too much? It works like a charm, but im not sure if is too overly complex or smt, or just straight up a bad idea
{
// Check if there's a platform below using OverlapCircle :P
Collider2D collider = Physics2D.OverlapCircle(transform.position, groundcolliderradius, groundlayer);
if (collider != null && collider.TryGetComponent<movablePlataformBase>(out var platformBase))
{
Transform platform = platformBase.transform;
// If she stepped on a new platform
if (currentPlatform != platform)
{
currentPlatform = platform;
platformOffset = rb2D.position - (Vector2)platform.position;
lastPlatformPos = platform.position;
}
// Move the player within the platform
rb2D.position += (Vector2)(platform.position - lastPlatformPos);
lastPlatformPos = platform.position;
}
else
{
currentPlatform = null;
}```
as long as it works there is no issue
it might be more precise to use a raycast instead of overlap
I know that you can do int = somebool ? True : false. But is there an equivalent with somebool ? Function() : do nothing?
if(somebool) Function();
Apart from just making a normal if-statement you could make a no-op delegate. So : () => {}
Or return null, and I'm fairly sure you can do delegateVar?.Invoke()
But tbh this is so obscure that I don't even remember
idk, the thing is even after the isDashing varaible is set back to false (aka normal slowdown is applied) its still really slow
i code a tiny bit everyday so it becomes one, also im new to C# so i dont have an identity yet so its kind of a mess but most of it will probably be slowly rewritten in the future so for now it works
yeah no even after setting the dash drag to the same as normal speed drag it still slows me down
Hello, i am very new to using unity, can someone please suggest a video,website,tutorial for understanding unity's new input system(i find the old input system very easy but want to learn the new one)
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thank you!
well you've got to know which part of the code is responspible for speeding up and slowing down the character
yeah, but the only thing which slows down the player is the dash slowdown which only applies if isDashing is true which its not
first check if it still happens if you remove dashslowdown or set it to 0
it does not
like i said in the original message
yVelocity *= 1 - MovementDrag * Time.deltaTime;```
doesnt this also cause slowdown
yeah, but its not affected by the cooldown
does it still happen if you remove that part?
remove what?
the part that I just posted
you want me to remove that part that moves the player to see if it moves the player faster?
no only the part that applies slowdown
changing dashslowdown doesnt affect it at all, unless if you set it to 0 because then it wont lose enough velocity to stop the dash
but what about 1 - movementdrag * deltatime
since thats the part of the code thats executed if isDashing is false
thats the part that slows the player down
which is the issue
so you dont, yk, fly off the screen the second you press w
no, it works perfectly, unless CurrentDashCooldown is more than 0
but the cooldown doesnt affect movement except not being able to dash
thats the weird part
I'm noticing that you're multiplying your movement verctor with deltatime twice, is that on purpose?
i am?
oh
removing that resulted in this:
what did you remove exactly
the * time.deltatime at the movement drag and dash slowdown
what's the value of the movement vector right before you change position?
lemme debug.log that
(Infinity, 0.00)
UnityEngine.Debug:Log (object)
PlayerController:HandleMovement () (at Assets/Scripts/Player/PlayerController.cs:111)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:42)
transform.position assign attempt for 'Player' is not valid. Input position is { Infinity, 0.000000, 0.000000 }.
UnityEngine.Transform:set_position (UnityEngine.Vector3)
PlayerController:HandleMovement () (at Assets/Scripts/Player/PlayerController.cs:112)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:42)
(-Infinity, 0.00)
UnityEngine.Debug:Log (object)
PlayerController:HandleMovement () (at Assets/Scripts/Player/PlayerController.cs:111)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:42)
transform.position assign attempt for 'Player' is not valid. Input position is { -Infinity, 0.000000, 0.000000 }.
UnityEngine.Transform:set_position (UnityEngine.Vector3)
PlayerController:HandleMovement () (at Assets/Scripts/Player/PlayerController.cs:112)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:42)
(Infinity, 0.00)
UnityEngine.Debug:Log (object)
PlayerController:HandleMovement () (at Assets/Scripts/Player/PlayerController.cs:111)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:42)
transform.position assign attempt for 'Player' is not valid. Input position is { Infinity, 0.000000, 0.000000 }.
UnityEngine.Transform:set_position (UnityEngine.Vector3)
PlayerController:HandleMovement () (at Assets/Scripts/Player/PlayerController.cs:112)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:42)
then go back and check the involved variables to see where the infinity is coming from
that shouldnt happen
I do see that you're mixing floats and ints a lot, maybe its a rounding error because of that somewhere
nvm
yeah thats the keyboard inputs
heres some logs:
Xinput: 1 | Yinput: 0
UnityEngine.Debug:Log (object)
PlayerController:HandleMovement () (at Assets/Scripts/Player/PlayerController.cs:105)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:42)
Xvel Before Drag: -Infinity | Yvel before drag: 0
UnityEngine.Debug:Log (object)
PlayerController:HandleMovement () (at Assets/Scripts/Player/PlayerController.cs:106)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:42)
(Infinity, 0.00)
UnityEngine.Debug:Log (object)
PlayerController:HandleMovement () (at Assets/Scripts/Player/PlayerController.cs:113)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:42)
transform.position assign attempt for 'Player' is not valid. Input position is { Infinity, 0.000000, 0.000000 }.
UnityEngine.Transform:set_position (UnityEngine.Vector3)
PlayerController:HandleMovement () (at Assets/Scripts/Player/PlayerController.cs:114)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:42)
so acceleration must be infinity?
xvel before drag is
or negative infinity
Unexpected Infinities usually means division by zero or at least division by something close enough to zero to count
no division :O
you have divisions, but they're written as multiplications
.. so division by zero would be multiplication by what?
0? but multplication by 0 is 0, not infinity?
where is xvel before drag exactly
xVelocity += xInput * MovementAcceleration;
then i log that
so if acceleration is 0.15 then the issue is from xinput
but xInput is 1
as shown in the logs
1f
I wonder if it's compounding multiplication by something less than 1? If that thing gets smaller and smaller every time eventually you'll run out of floats and unity will decide it's infinity. What are the values of MovementAcceleration and MovementDrag at the time you're getting Infinities?
theyre always acc = .15 and drag = 5
whats xvelocity before that?
we are seeing xVelocity += 1f * 0.15 = infinity
Multiplication by 1/0. Which can't exist normally but remember we're in floating point land where "close enough" can count
well i guess infinity
try setting a default value for velocity
i set it to .4, its spiraled out to infinity in like 2ms
its weird this only started happening when we stopped multiplying by deltatime 🤔
its got to be some sort of rounding error
try setting it to 1
1f or 1
1f
Some number is compounding when it's not supposed to be. I might just need to step through this in a debugger to find out what
ight
you can do that if it would help
Doesn't actually matter as long as the thing you're storing it in is a float
It might take me a bit, I'm about to head to work where I will probably be able to investigate in more detail. If this isn't solved in like an hour I'll look into it, because I don't really see anything obviously wrong at a glance
One thing to consider - try making a test scene that contains only this script and as little as possible to actually test it. Make sure it's not some other script futzing with those public values
heres some logs from the first milliseconds of the program with start xvel of 1
https://www.codedump.xyz/less/aLG1kzpmbmhs7mYw
oh yeah, is any other script affecting any of these variables?
nothing is touching it, the only thing that is changed across scripts is playerhealth
Okay that definitely looks like compounding multiplication. Somewhere in there xvel is multiplying by negative itself
(which is an entire other script)
oh wait maybe the drag application
thats multiplyiing itself by itself * -4
Ah, right, your math is expecting a value less than one and I just realized you said your drag was Five, not Point Five.
Your drag is expected to be a value less than 1 in your math
ah yep thats it
It's like, a drag percentage. The closer to 1 the faster it damps
yeah just realized that
but the original problem is still there
the CurrentDashCooldown is still messing with the speed
well its not the original issue
In what way? I could see the actual dash causing trouble but the cooldown stuff all seems unrelated
yeah, ik that, thats why ive been spending 3 hours trying to figure it out
it applies even when i articially set the CurrentDashCooldown to something greater than 0
without dashing at all
lemme show
the only part with slowdown of the code thats reached when isDashing is false is the part involving the drag
I'm not sure what I'm supposed to be noticing different here actually
notice when i turn around / start moving the other direction
the character moves slower while dash cooldown is more than 0
just to make sure, does it still happen if you set default for isDashing to false
it is false, at least the inspector says so
set a default value and try just in case theres a bug in the inspector or something
yeah, after defaulting it to false it does behave the same
and the velocities are as they should be when it happens?
lemme check
What’s the most effective way to smoothly make object with body slide down walls that has a lot of force agianst a wall?
lerp?
Wdym?
yeah, they roughly are, cant consistently test it but yeah
cant translate
the relatoin between the two is defined as a/b=c implying a=b*c (example: 10/2=5, 2*5=10)
if you try that with b=0 everything breaks (10/0=x, but no number exists that multiplied with 0 gives you 10, alternatively 0/0=x, then x can be any number you want (property not shown with any other number, even 1))
if its not the part with the drag, the only other part that it could be that I can see is this
can you check its not doing this?
What value would I lerp
i dont see how that would do anything as im not pressing space
do remember, division by zero isnt "it gives you infinity", its "its undefined"
yeah
lemme log that
the velocity probably
because most rules we have governing math just dont apply for it
even something like limits if converging on 0 give you different results based on where you're approaching from
if you're approaching from a positive number, it gives you infinity
if from the NEGATIVES, it gives you NEGATIVE infinity
what must be done for make the raycast to slowly follow the player instead of straight up hit it?
protected void laser(Transform laserPos, LayerMask victim, float laserDamage)
{
{
Vector3 targetPosition = objetivo.position; // objetivo is the player
targetPosition.z = 0;
Vector3 shootDirection = (targetPosition - laserPos.position).normalized;
RaycastHit2D hit = Physics2D.Raycast(laserPos.position, shootDirection, Mathf.Infinity, victim);
if (hit)
{
Debug.Log("Enemy hit: " + hit.collider.name);
ValeriaController player = hit.transform.GetComponent<ValeriaController>();
if (player != null)
{
// Apply damage
player.TakeDamage(30); // Adjust damage as needed
}
// Optional: visualize the attack
lineRenderer.SetPosition(0, laserPos.position);
lineRenderer.SetPosition(1, hit.point);
}
else
{
// Missed, draw a line in that direction anyway
lineRenderer.SetPosition(0, laserPos.position);
lineRenderer.SetPosition(1, laserPos.position + shootDirection * 100);
}
}
}```
yeah no its not called if i dont actually dash
well i'm stumped, my usual approach in these cases is to print variables at every step to make sure everything is as it should be, and to remove parts one by one until I find the one thats causing the problem
what do you mena by slowly follow
they are always instant
i mean following it
mm, i mean, like a laser
if is instant, it will look and feel bad an be an instakill
think you need to break the problem down more
like figure out would be a case of having something turn to aim at the player over time
then its not actually a laser so treat it like a bullet
i assume he means lerp the laser ala star wars
lol
if its that then i would just use a projectile
@polar acorn may you run it through your debugger later
Holup
i can send you the entire project if you want
Thats a great idea
Wait
Theres an issue
I mean
If i did a proyectile and a line following it, it wouldnt have inf distance or it will?
why would it
I mean
Like.......
James Bond's lasers?....
send me the project too I wanna check
alrighty
try it
The proyectiles idea?
yes
But wait
Using proyectiles wouldnt make that anything in the line to get hit, just what the proyectile hitted
Or you mean
Not just the line but the raycast be on the proyectiles position aswell?
It may work
I will test it
i just did
like i mentioned please describe what you mean, like should the laster take time to reach its target
or is the tracking of the laser taking time, so its always behind a moving target
2 very different things
But if the projectile is the laser how is that any different
In theory it should.
Visuals?
Idk
I just want a laser attack, and an instantaneus laser wouldnt do it
ok but you are not answering much about how that should play out
So make a projectile that looks like a laser
since there are a few approaches and people cant help without knowing which one
You want it to travel like Star Wars? Pew, pew . . .
Wut
like a star wars one is just a projectile
No, not that laser
Like James Bond
Is s raycast
That moves slow
That seems like a star wars laser to me
No
I think im messing thing up
I want a raycast that shots where the player were
I mean
A raycast doesn't move slow. It's instant . . .
You just described a Star Wars laser . . .
I want the distance instantaneus
A raycast instantaneously detects a line between two points
But arent star was lasers just long goowing bullets?
How do I get the mouse position local to a specific parent
'tisn't lasers in SW, it's "bolts of super-heated plasma or energised gas" 🤓
Yeah that kinda sounds like what you're describing
Angle? 🤔
Like if you pointed with a laser not to a potato, but you rotated your hand slowly to the potato
movement of the ray
Okay, so multiple raycasts
Wat
With a delay between each
Lerp to the target rotation over time
So you'd do a raycast and then after a frame do another raycast at a different angle
Ah, yeah, i think
Its on update btw
This raycast thing
So yeah
A raycast is instantaneous, you can't "move" a raycast, you just make a new one
I think applying rotation to the raycast is probably better
Makes sense
You raycast each frame in a new direction
I want the raycast to hit where the player was then
They direction is moving overtime to the direction of the target
Yes i know that, it updates
Is just that i explained myself wrong
But now i think i know how to fix it
Tho i dobt know how to write it
I mean
I need a raycast that hits whenever the player was
So it would follow it
If we make a lot constantly
Guys, how do you make it so your camera doesnt move up/down/left/right with your mouse with the slightest tap? Would you just make it so only after a certain value it starts moving or is there a different way of doing it?
Lerp it's raycast direction between the last one and the player location so it turns over time
Oh! Thanks
also sens doesnt affect this as much as i would like
that just sounds like your sens is too low
how can u get a list of all the children of a gameobject? i only see get child or get child by index
for loop thru them all
You can actually loop over transform as if it were a list. Kind of a weird way to do it and I wish they'd just make a GetChildren() function because no one would even think to look for that.
foreach(Transform child in parent.transform)

Looop over the transform of the GameObject . . .
oh thanks
How can I get the position of the MouseCursor relative to a parent
like it's always (x = 3 , y = 1, z = 5) relative to the parent even though it's moving to the world
well no z ig
You can convert a point from world space to local space using InverseTransformPoint:
https://docs.unity3d.com/ScriptReference/Transform.InverseTransformPoint.html
hi! im learning C# and unity, can someone tell me what's the best place to start ?(also sorry if my english is bad, its not my first language)
See the pinned msgs and also 👇 !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I have dropped your code into a fresh project and come to the conclusion that this is either psychosomatic or framerate-related and there is no difference.
I made three objects at different starting points. One of them had the script you provided as-is. One of them has the script you provided, but with its current dash cooldown set to 999999. One of them had a modified copy of that script with everything related to dashing and cooldowns removed.
All three moved completely identically. They were in perfect sync at all times until I dashed, at which point, the two that had dashes still did their dash and remained synced with each other.
what would that be?
but my code is framerate independant
i think
add a check like that to keep your values from going into unnecessary ranges
alright
It would still visually look different, even if the overall results are the same movement speed
but yeah I made the velocities public and the values were the same with or without cooldown
yeah but the like turning speed is whats different
I ran it with and without dashes and everything remained synced
thats wierd
make xvel and yvel public and observe the values as you move and as you stop moving
Top is unmodified.
Middle is given a dash cooldown as shown in the video.
Bottom is custom script with no dashing whatsoever
how do you do smooth turning towards another object
like a player seeking projectile
smooth how
not turn instantly and always face it, but turn at a constant speed towards it
lerp
ofc
The percent of the way between the start and end points
yeah i know that, but in my context, what would it be
deltatime
You'd probably want it to slowly increase from 0 to 1 over time
you can multiply time with speed to change the how fast it turns
well how can I use a transform function on the mouse cursor position? I store the mouse's position in a Vector3 virutalKeyPosition how can I turn make it local to specific parent?
I can't call the function properly I think I'm missing something
If the mouse's position is in world space, you'd pass it to an object's InverseTransformPoint to get its position relative to that object
I think you mean th4n0id
so
transform.InverseTrasnformPoint(virtualKeyPosition);
would get me the Object's position relative to the cursor or the other way around?
yeah but that moves towards a static angle, not a moving object
I did, I don't know how I misclicked that
That would return a Vector representing the virtualKeyPosition in this object's local space.
So if it were 10 units directly above this object, it'd return 0, 10, 0
Even if that virtualKeyPosition is actually at something like 120, 44, 318
you can just update the angle
ig, i think too low level, im not used to game engines, making everything about collision, coordinates n stuff actually not hell
making an object target the player and move towards the player, i was thinking turning towards the player and then just moving forwards
then recalculate the angle when it changes and lerp to that
Why is spawnSide 0 in the method?
https://paste.mod.gg/cfylurutlvko/0
A tool for sharing your source code with the world!
Presumably because it's set to 0
How do racing games handle their ai? Like are they just simulating input to get the cars to move toward waypoints and using raycasts to avoid ramming other vehicles?
there are all kinds of ways of doing it
Such as?
did you check?
Are you sure that's running and that it's set to something other than 0?
yes, in the awake method spawnSide is the intended number
yes it writes out the intended number in the console
but not when its supposed to write in the console from the method
the movement method
And are you sure it's the same instance of this script in both cases?
What calls movement?
another SO
yes they spawn once every 2 seconds
and the two messages are different
in the console
An SO?
How is an SO calling a function on a component?
How is it referencing the one in the scene?
for example, you could properly simulate the whole race for every car, or you can use a simplified representation in memory, or you can just not do anything when the ai cars are offscreen and periodically put them behind the player
there are many ways
the gamemanager has access to the problematic object via script
heres that code: https://paste.mod.gg/ydoilwnglpcp/0
A tool for sharing your source code with the world!
i forgot to comment that the method is being called on row 88
Okay so it's not an SO, it's another component.
So, you're calling movement on enemyScript. What is that set to?
isnt SO scriptable object?
components are parts of objects
also what does "set to" mean? isnt the method supposed to run when its called
isnt it that simple?
Yes, it is. Which is why I assumed it was one, because you said it was. But it isn't.
I mean what is that variable set to. What did you assign that variable to
i think ive misunderstood what scriptable objects are
as in what it is supposed to do? or what defines it?
As in what is the variable enemyScript set to
Probably.
enemyScript is a type of EnemyScript which is another class
in which movement() is supposed to run
And what is that variable set to
im sorry but i really dont understand could you give a brief example
I mean
what is the value
that you set the variable enemyScript to
I cannot make this easier
Variables are containers that hold value
what is the value this container holds
i did this: [SerializeField] EnemyScript enemyScript;
and then i dragged in the enemy prefab code
AND THEN WHAT DID YOU SET IT TO
Finally
So you're calling movement on the prefab
The prefab that never exists in the scene
and never has Awake run on it
but it prints out the intended number in the console through the awake() function????????
yes, the ones you spawn do
but they never get movement called on them
they do print out 0
as in that they were not assigned a value
but the movement method is being run
You are calling movement on the prefab.
Prefabs do not exist in the scene. So they do not ever run Awake
You are spawning copies of the prefab.
These copies do exist in the scene, so they do run Awake.
But nothing ever calls movement on them.
so youre saying that there is one object that runs movement everytime movement is being called, and that only awake is being run on the copies?
I am saying exactly what I am saying.
You have a prefab in your project files that you are calling movement on. This object will never run Awake.
Anything cloned from that prefab will run Awake, but nothing is ever calling movement on them.
how do i then make it so that only clones exist and that they each run awake and movement?
You would need to call movement on the objects that actually exist in the world. Not the prefab.
_virtualKeyPositionLocalToPlayer = player.trasnform.InverseTransformPoint(Input.MousePosition);
if (Input.GetMouseButton(0))
{
points.Add(new Point(_virtualKeyPositionLocalToPlayer.x, -_virtualKeyPositionLocalToPlayer.y,strokeId));
currentGestureLineRenderer.positionCount = ++vertexCount;
currentGestureLineRenderer.useWorldSpace = false;
Vector3 drawPoint =
Camera.main.ScreenToViewportPoint( new Vector3(_virtualKeyPositionLocalToPlayer.x,_virtualKeyPositionLocalToPlayer.y, 10));
currentGestureLineRenderer.SetPosition(vertexCount - 1, drawPoint);```
I don't get what's wrong with this trying to draw using a lineRenderer based on Mouse's position relative to the player, the drawing of the lineRenderer is supposed to move with the player and not be disturbed by movement up and down or anything.
and I dunno why discord ruined the code like that lol
so its impossible to run a system where movement is being called on continously spawning prefabs?
Or wait
would it work if i didnt do serializefield
and if i tried to define enemyScript via code?
then the movement method should connect to all gameobjects that have the class EnemyScript in them right?
You can, you just need to call movement on those objects you spawn
Not the prefab
yes im just wondering is this a solution?
is it an idea worth of pursuit?
I don't know what solution you're proposing
I'm not sure I understand it correctly but I would say no
do what digiholic said
look i understand that the movement method is only being run on the prefab, thats what digiholic has told me so far
what im after is a solution
Call it on the objects that you spawn. The ones that actually exist.
yes im trying to figure out how i can do that
Instantiate returns a reference to the object it spawns
objecttype variablename = prefab.Instantiate()
My idea for a solution is to define enemyScript like this
EnemyScript enemyScript;
void Awake()
{
enemyScript = GameObject.Find("Enemy").GetComponent<EnemyScript>();
}
would this not reach every object that spawns with that code file in it?
then you can variablename.movement()
objectType obj = Instantiate(prefab, pos, rotation);
obj.movementFunction();```
would be kind of a way to go
yeah
This would find an object named Enemy
You can just check what these functions do by the way, you can look them up
so it would not find every object named Enemy
yes
Just one
You don't need to do any finding
abandon this idea
you have the references
Instantiate returns the references to the objects it makes
Use them.
ill look into this idea
all ive learned about instantiate so far is that it spawns things, not that i can send signals to these spawned objects
but thx everyone
it gives you the reference to the thing it spawns
with that reference you can get anything on the object and do what ever you want with it
most people would create a list to hold references to all enemies you spawned then you have access to all of them
does
LineRenderer.SetPosition(index, position);
can it work on Local Positions?
LineRenderer.SetPosition(vertex-1, new Vector3(0,1,0));
Can this be (0,1,0) be a position relative to a parent or does it have to be world position?
try it out
there is a toggle on it
to use worldSpace or local space
just turn off use world space in the inspector
oh
so now position will take the localSpace of the parent of the gameObject or do i have to pass something in?
works with the same values
the toggle effects both poitns added in code and ones added in the inspector
I mean like,
if the LineRenderer's gameObject is not a child, it will also use world space?
not sure what you mean by that
but the points in a line renderer work in world space or local space to the line renderer object
via that toggle
if you need anything more specific then that like putting something in local space of a other object that is not the one the renderer is on then i would just use world space and get familar with the TransformPoint and InverseTransformPoint methods on transform
yeah I got you I just misunderstood something
_virtualKeyPositionLocalToPlayer = player.transform.InverseTransformPoint(Input.mousePosition);
Transform tmpGesture = Instantiate(gestureOnScreenPrefab, player.transform, worldPositionStays:false) as Transform;
points.Add(new Point(_virtualKeyPositionLocalToPlayer.x, -_virtualKeyPositionLocalToPlayer.y, strokeId));
currentGestureLineRenderer.positionCount = ++vertexCount;
currentGestureLineRenderer.SetPosition(vertexCount - 1, _virtualKeyPositionLocalToPlayer);```
So this is the script I'm trying to use to draw a gesture with my mouse that moves with the player on screen but doesn't get jagged or disrupted from the player's movement
has a problem where it draws yes, follows the player, but the scale is horribly off and it doesn't draw on the mouse position
so jsut converting mouse position with the players transform does not make a whole lot of sense
I thought that would return the mouse's position relative to the player's transform?
no because mouse position is in screen space
you need Camera.main.ScreenToWorldPoint(mousePosition)
Oh yeah lemme try that rq
that method also only works for ortho cameras since it gets a point on the camers near plane
you may want to set your mouse position z coordinate to Camera.main.nearClipPlane
yeah can just make it a tiny number
or make it a control so you can decide how projected out from the camera the point should be
yeah it works thanks guys
i know it's network related but i don't want to make an entire thread just to ask how to convert networkvariable<bool> to a proper bool?
networkVar.Value
Just FYI, the networking channel has a general thread for short questions like that
https://discord.com/channels/489222168727519232/1392142304772358215
I have a 2D tile based game. Every tile has collision, material and some properties.
If my game has 200x200 visible tiles, am I supposed to create 40000 game objects?
have you heard of tilemaps before?
yes but I instantly ignored them after I realized they are not scalable
what if I want to have 200x200 visible tiles but 20000x20000 tile map
i want to see you make a tilemap this big this would take forever
doesn't matter, maybe I want much more, like 100k x 100k
i think i still dont get what you mean. tilemaps are basicly infinite only depends on how much you "draw" onto it
every tutorial I watched said something different, built-in tile maps are not infinite
whatever then do it with 40000 gameobjects
tilemaps are the solution that everyone uses because it works for anyone
it's not whatever, if you say they are scalable, maybe I watched crap tutorials
generally 95% of unity videos are soooo useless
thats a fact tho
good luck w/ a 100k² tilemap
ud def want some type of chunking / procedural streaming
Fun fact: games like Stardew Valley, Terraria, or Factorio have millions of tiles but only a fraction are ever instantiated as actual objects in the scene at once.
I absolutely don't care what others do. I just want ot know if I can scale built-in tile maps
may i ask what you need a tilemap this big for?
then you do care.. else why ask and just do ur own thing
a tilemap like that is gonna tank performance.
you are not "others", I do care what you think
ahh soo "others" as in non-game-devs
can you explain a bit by what u mean by "scale" when ur refering to tilemaps?
200^2 tiles visible at once?
lol.. at that point they'd be 2-3 pixels across 😄
if no, dont instantiate them all at once, if yes, you're probably doing something wrong
game dev 101 is not instantiating the entire map all at once
you'd need to ask someone smarter than me in how to do that tho
the only solutuions i know are rawdogs
can we get an audio of your pc?
you miss the whole point of what I want
instead of asking something important you ask about amount of rendered tiles or map size
that's why I said 200x200 or 100k x 100k to show you that numbers doesn't matter
if I said that I have 10x10 visible tiles and 100x100 map, you would start to intruducing some f*cking crap solutions I've seen 100 times already on youtube
you didnt exactly clarify on what you want
I will do doc research about these built-in tile maps, maybe they aren't that bad as I thought
and the solution does depend on your scale
It crashed 🤣
oh i hope you didnt have any unchanged saves🙏
what are your specs tho?
pretty dang high.. lol
if its a small map (64x64 or whatever) just instantiate everything at once
if its larger, store the type of tile in some list array whatever and init when entering your viewport
if its infinte then generate on the fly
maybe they work for nasa
Claude ❤️
nah, we're good i was 96% sure it was gonna crash 🤣
why do you want them sorted by distance anyways
just store their refs and compare distance when you actually need them
those specs arent even that crazy im running a 2070 super and ryzen 5 5600x
ya, true.. i like to believe my strength is endless 😆
me to rn im fighting to get every fps possible with shaders
yeah thats pretty good actually. my flex are 32gb ram
i need help with the unity microphone class (idk if this is the right channel, i cant find a programming help channel)
yes this is a programming channel u can ask questions in.
yes the microphone class would be included..
!ask
whats the question?
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
im initializing a microphone like this but for some reason it is recording much faster than i specify. it seems like the audio clip is created with the parameters here but the mic doesn't follow these parameters at all.
Microphone.Start(NetworkingUDPMicrophoneName, true, 1, 24000);
because the mic doesn't follow these parameters the receiving clients aren't reading the data fast enough or reading it correctly
prioritization by distance
frequency of update > when nearby player
how many entries do you expect in that sorted list
if its less than uhh half a thousand? just sort on the fly
(number pulled out of my ass)
if anyone knows any solutions to finding the actual parameters like sample rate and channel count please let me know as unity has no accurate way of pulling this off of the audioclip the microphone creates
distance isnt really something you can easily re-sort
hey i have a softbody made up of points connected with spring joints, but if i change the rotation for example, its like the springs loose all their tension. is there something i can do about this?
i think i solved it, the unity mic forces mono audio so there is no pulling the channel count but to get sample rate i just compare my target rate to what the mic actually can handle and then i manually resample.
Microphone.GetDeviceCaps(NetworkingUDPMicrophoneName, out int MinSampleRate, out int MaxSampleRate);
ty
doesn't matter, the point was Claude saucy language 😄
fair
context is unity pathfinder, that underspecced blackbox is a nightmare
i once got deepseek to say something summarizing to "this is absolutely insane but if you do this you'll be forever revered by [community]. godspeed."
lemme dig it up hol on
why does the value of the additional gravity here not matter past a certain point? and also how do I stop the upwards momentum the player has after jumping when trying to fast fall?
I want to implement a system where the player hits a tree with a rock, the tree loses HP and is destroyed at 0, how can I handle this with boxcollider?
void Update()
{
if (Input.GetMouseButtonDown(0))
{
animator.SetTrigger("Hit");
boxCollider.enabled = true;
}
else
{
boxCollider.enabled = false;
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
the above message for you too
you also shouldnt use a box collider there if its just supposed to be a 1 frame check, just use one of the physics methods like OverlapBox
A tool for sharing your source code with the world!
using addForce and setting the linearVelocity directly elsewhere probably isn't helping here, i would change this to just use add fastFallGravity to the linearVelocity instead.
also you dont need to GetComponent, you're already storing and using the rb in other parts of your code
as for stopping the upward momentum, you could just directly set the linear velocity so the player starts falling immediately like you do with the jump already. It might look very sudden to the user though
ty king
claude is shit
its better than most AIs but thats not saying much
hey i got a softbody system i made and it also has background color made by creating a mesh of the individual points of the softbody. when the object is rotated even before hitting play, the mesh doesnt really want to cooperate and it looks like as if it rotates with the object, but twice the amount. what can i do about this? heres what it looks like and the code i use for making the mesh (which also isnt perfect) https://hastebin.skyra.pw/jiketohula.csharp
how do you rotate it
transform in inspector
how is the mesh updated?
true! they're impressively bad but when you don't want to deal with shit syntax, they can work
what do you mean exactly?
private void Update()
{
CreateShape();
mesh.Clear();
mesh.vertices = verts;
if(tris != previousTris)
{
mesh.triangles = tris;
previousTris = tris;
}
mesh.RecalculateBounds();
mesh.uv = uv;
}```thats the update function if it helps
you cant compare arrays like that btw thats just a reference comparison
how should i compare them instead? but that isnt the solution right?
as long as the mesh origin matches the other objects origin and vert positions are local it should update correctly
but to compare array contents you can loop and compare both
i appreciate your words magic man but i dont understand a thing
okay
why do you need to check each frame it worked?
use a for loop to compare each item in each array, if all match you know the arrays contain the same data, else not!
for(int i = 0; i < tris.Length; i++)
{
if (tris[i] != previousTris[i])
{
mesh.triangles = tris;
previousTris = tris;
}
}``` like this?
erm no
int[] a = {1,2,3};
int[] b = {4,5,6};
bool areSame = true;
for(int i = 0; i < a.Length; i++)
{
if(a[i] != b[i])
{
areSame = false;
break;
}
}
if(areSame)
{
//Do shit
}
for(int i = 0; i < tris.Length; i++)
{
if (tris[i] != previousTris[i])
{
trisUpdated = true;
break;
}
}
if(trisUpdated)
{
mesh.triangles = tris;
previousTris = tris;
}```like this?
forgot including trisUpdated is a local variable being false by default
Something seems off with lines 32 and 33 where they're using verts[i] instead of verts[i+1]. When i is 0 they would be using default value. Uncertain of the intentions as you're also assigning verts[0] to Vector3.zero on line 35 shortly after. 
Did you perhaps want to use i+1 for lines 32 and 33 as well or ...
line 32 is more of a relic forgot to delete that. the vector2 vert is used for nothing
perhaps im not sure. i dont know how to test if the uvs are correct
Just for clarity, the math operation with verts[i].x + 1 / 2 would have the 0 be added to the x component - no work is done (physics pun). @hallow acorn
If you're wanting to add 0.5f every time, you'll need either value 1 or 2 to be 1f or 2f.
If you're wanting to divide after adding one, you'll need to use parenthesis (verts[i].x + 1f) / 2f.
oh thank you
Please help me, I’m using a invisible player object to handle movement but I want another hovering over it to serve as the display and be posilhed. This mesh can be pushed to the floor but I have no idea where to start
I’m in 2d btw
what
wat
This is the beginner coding channel, if the issue is directly related to code you'll need to post more context (!code)
Else try one of the other channels id:browse
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
order of operations is a thing
yeah idk what i was doing there
while i did improve a lot of things about my code i still dont have the solution to my original problem though
didnt get it but i fixed it right now
what was it
just had to change line 34 from verts[i+1] = points[i].position - transform.position;
to verts[i+1] = points[i].localPosition;
Can you better explain ? I only understood half of that..
You can use SequenceEquals from Linq
fixed it
I’m using a spring joint rn It’s looking good
idk if this is begginer, but I am
I am using Mathf.PerlinNoise and I noticed that it rarely reaches the edges(mind it is 2d side viwe, so I only need a 1D perlin noise, using 2d for seeding purposes)
int layerYPerlinDelta = 2;
for (int x = 0; x < 70; x++)
{
int perlinSample = Mathf.RoundToInt((2 * layerYPerlinDelta + 1) * (Mathf.PerlinNoise(perlinScale * x, perlinSeed) - 0.5f));
//below is +layerYPerlinDelta and not +layerYPerlinDelta+1, since it's a float function
perlinSample = Mathf.Clamp(perlinSample, -layerYPerlinDelta, +layerYPerlinDelta);
Debug.Log(perlinSample);
//(i'm not actually debug logging, but it works)
}
If the distribution was uniform, this would give me a pretty decent world terrain
But it rarely hits 2 or -2(i never saw it hit -2)
ChatGPT suggested i raise it to some exponent, which is a pretty god idea, but is the problem with perlin noise or my code(i think my code is fine)
public class SpawnSteak : MonoBehaviour
{
public GameObject steak;
public GameObject cookedSteak;
private GameObject spawnedInstance;
public AudioSource soundPlayer;
public AudioSource soundPlayer2;
public float timeBegin = 5f;
void DestroyObject(){
Destroy(spawnedInstance);
soundPlayer.Stop();
Instantiate(cookedSteak);
soundPlayer2.Play();
}
// Start is called before the first frame update
void Start()
{
}
public void OnMouseDown(){
spawnedInstance = Instantiate(steak);
soundPlayer.Play();
}
// Update is called once per frame
void Update()
{
if (spawnedInstance != null){
Invoke("DestroyObject", 5f);
//CancelInvoke("DestroyObject");
}
}
}
This code is meant to instantiate an object, destroy it after 5 seconds, and instantiate a new one. But after five seconds, it keeps instantiating multiple clones of the new object, how do I make the invoke method only perform the action once?
public void OnMouseDown(){
spawnedInstance = Instantiate(steak);
soundPlayer.Play();
//Invoke("DestroyObject");
}``` why not call it at the end of this?
Okay, let me try that
option 2 use a coroutine
cant you just check for a state
The first suggestion worked, thank youu
perlin noise itself avoids extremes by design
to have extremes more often remap (power/curve) or layer noises together
im not 💯 sure about that first part but the 2nd part sounds like it could be helpful
edit: mb i ment to reply to @echo ravine
or use a different kind of noise
its b/c u were checking in update if the thing was assigned.. (which it would be for quite a few frames)
so it just spammed the Invoke over and over until it was eventually gone.. by calling it at the end of the OnMouse method ur ensuring its only gonna run once.. just as its instantiated once
Ohh, I understand now, thanks so much
srry bout the rogue ping.. meant to ping enegaga
im not sure what different noises available are..https://eev.ee/blog/2016/05/29/perlin-noise/ heres where that screenshot came from tho..
explains perlin pretty well
there are quite a few solutions for different kinds of noises and noise generators online, here are a couple https://www.ronja-tutorials.com/noise.html
why is my potion not being set active? I am creating it during runtime so instantiating it
public void SpawnSmallManaPotionPrefabForPlayer()
{
if (hasSmallManaPotion == false)
{
Quaternion rotation = Quaternion.Euler(0, 0, 0);
smallManaPotionClone = Instantiate(smallManaPotionPrefab, rightHandOffsetObjectTransform);
smallManaPotionClone.transform.rotation = rotation;
smallManaPotionClone.transform.position = rightHandOffsetObjectTransform.transform.position;
hasSmallManaPotion = true;
hasDrinkable = true;
smallManaPotionClone.SetActive(false);
}
}
public void RecoverManaFromSmallPotion()
{
if (hasSmallManaPotion == true && hasDrinkable == true)
{
smallManaPotionClone.SetActive(true);
hasSmallManaPotion = false;
extendedCharacterController.currentMana = Mathf.Min(extendedCharacterController.currentMana + 30, extendedCharacterController.currentMaximumMana);
}
}
You tell us. Use Debug.Log("Some Message") to figure out which line isn't being run.
i will be making a game where money can reach above googol (10¹⁰⁰). I searched how to store that and found "BigInteger". Is that a good way to do the money calculations or should i do it different way?
logs are the solution in this case ^ log each method, each if statement, and jst see
yeah go with that
not a clue.. but looks like something i'd try
if you dont actually need exact precision you can also fake it
^ this.. could use a big multiplier..
thanks!
I was wondering if it was my bad
I think i am going to keep with perlin and accept that, since it's not a big problem, i''l just increase the limits and wither cramp or not do anything
lol I found the problem, I have it set to if I have a below the maximum amount of mana, the function will be run but if it is full then it wont run so basically it was a human error
classic pebkac
its human error almost 99.9% of the time 😅
logic error
always helps to debug everything
odds are you'll be like "wait, where is.. x,y,z?"
sort of, I just had full mana when I tried to activate the Recover function
cuz I forgot to use up some mana before trying it
If I set InputFields line type to multi line and give it a ContentSizeFitter with vertical preferred size, the text jumps up a little when I click enter for new line
It is set to top left anchor
#📲┃ui-ux and be sure to include a question
is there any way to use python with unity without spending money for an asset? it's what im used to using because im just a hobbiest and cs is atrocious
no
fml
Once you get used to it c# is great
you arent gonna get far if the first thing you want to do is fight the system you're learning. Theres an intro to c# resource pinned in the channel
if you already got a grasp on python, learning a other langauge will be no big deal
how do i access the code of an instantiated object
i have methods that i want to access in instantiated prefabs
Didn't people spend almost an hour yesterday to go through this
SomeComponent clone = Instantiate(prefab).GetComponent<SomeComponent>();
clone.SomeMethod();
they explained what was wrong, then i tried to look into the idea for the solution they proposed but i could barely process what i was reading in the unity api
all you need to do is to cache the GameObject or any of its components, as Nitku showed, you are caching the Component here, if you would the whole GameObject so you can acces all of it you could simply do
GameObject instantiatedGo = Instantiate(.....);
then acces its components by doing instantiatedGo.GetComponent<SomeComponent>();
this is not very good
well, it's fine, but it could be better
for something like that you should have prefab be typed as the component directly
makes it foolproof @tiny crag ^
(cc @frail hawk)
there are a lot of things i dont understand in your replies, what would be the best way to learn more?
because i think this project is beyond me at this point
then you will have to start small and learn the c# basics
i watched two tutorial series on c# in unity, but i didnt finnish them because at that point i didnt understand what they were talking about
so i decided to try and make a simple game to reinforce what i had learned so far
what i wanted to make was a game where the player was a cube avoiding other cubes coming from the edges of the screen
it worked but the spawning and movement between all the objects were not synced, an idea i tried to realize by making a new project and changing the code
i think im gonna do the tank game tutorial made by unity for now and maybe come back to this project in the future but thanks a lot for trying to help me!!!
if you are not experienced in programming i would recommend you learn some basic c# instead of unity c#
Yea c# and programming in general should be learnt and understood on its own if a total beginner
i have made projects in python, whereof the most advanced one was a poker bot that typed out probabilities and made decisions for poker
i also made a simple game in pygame
Then it should hopefully make sense how we spawn new objects and can get components of those instances
Its nothing crazy. You know what a gameobject is and components are right? You can add your own "scripts" to gameobjects but these scripts are also components.
Well when we spawn in a copy of a prefab we want to get those NEW components and do stuff with them, thats what GetComponent() is for.
maybe then its not the concepts but the code that i dont understand
GameObject myCoolPrefab = Resources.Load("MyCoolPrefab");
GameObject spawnedObject = Instantiate(myCoolPrefab);
Light light = spawnedObject.GetComponent<Light>();
- Load prefab from resources folder
- Spawn copy of prefab in our scene
- Get reference to Light component from our new copy
thank you, this made it very simple!
we can use a serialized reference of a prefab instead which is often preferred
[SerializeField]
GameObject myCoolPrefab;
yes but i did run into an issue when i used this on a prefab
apparently the prefab already existed but not the gameObject with the code that i was trying to apply to the prefab though a serialized reference
but thanks a lot rob5300
well yea if you try to modify the prefab asset instead then you will be confused
so make sure to not do that and name things well so its obvious whats the "prefab asset" and whats the created instances in scene
yes i will
what is the point of creating a private variable to then create a public variable referencing the private one?
It's read-only but we can also do this with auto properties
oh like a getter and setter?
that way you can only publicly red the variable, can't modify it from outside
alr thank you
I'm currently getting the following error -
Internal: JobTempAlloc has allocations that are more than the maximum lifespan of 4 frames old - this is not allowed and likely a leak
I've set Unity to output JobTempMemoryLeakValidation, but I'm a bit lost as to where the error is. Can anybody help me out here?
i think #💻┃unity-talk might have answers
Thank you! I'll repost there.
when I hit a breakpoint in Unity with vscode, the entire vscode is not visible for my mouse in Linux and Windows
what kind of crap is this man
I am not able to continue execution or do literally anything. I have to kill Unityand restart again until I hit another breakpoint.
same with Unity window, also not visible for mouse
how to dump a class to the console in unity?
there is a God tier function in php called dd which prints everything
example:
class A
{
public string $str = "aaaa";
private int $i = 123;
public function __construct(public B $b = new B()) {}
}
class B
{
public string $bField = "bbbb";
}
dd(new A());
result:
Now I need something like this in unity. Debug.Log is nothing near dd
C# is a compiled language so it's not quite as simple. Use the IDE's debugger to inspect objects
There are also lots of other options on Google, e.g. https://stackoverflow.com/questions/360277/what-is-the-best-way-to-dump-entire-objects-to-a-log-in-c
not sure about the formatting that u want
but couldnt u do something like
[SerializeField] private string scriptFileName = "ScriptDumper.cs";
[ContextMenu("Dump Script")]
private void DumpScript()
{
string path = Path.Combine(Application.dataPath, scriptFileName);
if (!File.Exists(path))
{
Debug.LogError("Script file not found: " + path);
return;
}
string[] lines = File.ReadAllLines(path);
for (int i = 0; i < lines.Length; i++)
{
Debug.Log($"{i + 1:000}: {lines[i]}");
}
}
}```
I'm pretty sure they want to see the current values of object fields and properties, not the class source code
well I mean like doing it like this just makes the player fall so fast they clip through the ground
setting the vector 3 to smth rly low like -1 doesn't help either
ohhhh... ya thats a bit too much for my pea-brain
simple fix would be to change ur collision detection to Continuous
could try making the ground collider a bit bigger (use a cube as the collider rather the plane)
also use ur ground-check as an advantage...
if not grounded -> do the gravity fast fall or w/e
if is grounded -> keep the gravity a concrete value.. like -9
// Vertical movement (Y)
float vertical = currentVelocity.y;
if (controller.isGrounded && vertical < 0f)
vertical = groundedGravity; // Stick to ground
else
vertical += gravity * Time.deltaTime; // Apply gravity``` like so
I have this issue where when I am not grounded the player speed is very fast. to fix this should I reduce input, and boost the down force a bit? or Apply a different force when in the air? I see so many people talking about different methods but don't know which one to choose.
people usually change out the drag/ dampening values
If I increase the drag the player slowly falls when in the air
depending on air or ground
ground = smaller value (because of friction helping out)
air = bigger value (to simulate air drag)
u can also adjust the gravity while airbourne
so the lateral movements are nerfed but u adjust the gravity to work w/ those new values
Should I use a physics material?
i actually do it that way for my controller..
air has its own values
ground has differ values
physics materials could work if u change em out
If you've already found different solutions then try them out and pick the one that works for you. That's why there are so many of them because it depends on the game which one works the best
^ theres no real one solution fits all type of deal
unity's gravity is kinda floaty imo anyways
i use strong gravity forces
what's groundedGravity supposed to be here?
groundedGravity is the concrete value
it stays the same... like -9 , -9, -9 all the time
the Simulated gravity is when im airborne.. its compounded
hey i was wondering if there is a way to make a gameobject through code that exists after leaving playmode would be really usefull, thanks in advance
wdym by friction? if my grounded values are low I'm just sliding around.
-9 -9 = -18 -9 = -27 so on
i dont use friction (only for certain occasions)
its normally just drag / dampening for my controls
its just a trial and error game..
you have ur logic.. (either u stick to that logic or adapt it)
but w/e you do ur values will need to be fine-tuned to that logic
if u change the logic.. u then need again to change and tune the values of the rigidbody/friction/code values etc to make it work
mine wont be the same as urs.. urs wont be the same as someone elses..
there are a few ways you could potentially do this, but what are you trying to do ? maybe there is a better solution
still at my mfing softbodys haha. trying to generate them threw code as i think its less time consuming than indiviudally connnecting a lot of points with each other by hand
heres ur options
- seperate ground / air movement and values
- adjust drag/ dampening (by state)
- custom gravity (forces stronger when airborne)
- hybrid approach (air input reduced, air drag a bit higher, gravity slightly boosted
(makes jumps snappy, reduces mid-air "Ice-skating"
it most likely will be a hybrid of those... (depending on whats good enough for ur controller)
you don't need to run Playmode to create gameobjects btw
helps to start with some normal feeling values.. and then tune them very slowly.. (just minor increments)
can i run the code beforehand or wdym?
you absolutely can..
HOW???
this is so fucking cool i didnt know you could do that
yes things like Context Menu, Execute in Editor/Always, plugging into the InitializeOnLoad etc.
lol. its a game-changer when u dont need to press play and wait 10 seconds or so just to build out something.. that u need to test just to back out and try again
u can make the code create this object under a parent container.. and just delete that container and try again insteed
you can also make ur own Menu to call/run code
ill definitely try this thats so cool
i'd def try to introduce it into ur work-flow somehow
hey if i want to makee an array of coordinates (in 2D) for individual points, how can i do that through code for example if i want to make a square with 16 points, how can i distribute the 16 points evenly and place those points on the square? idk if its clear what im trying to say but i hope so
probably dividing the perimeter of the shape by the number of points to distribute them evenly but i have no idea how to go on with the rest of it
yup something like that..
you'd probably want to figure out how many rows / columns u'd need
get the corner somehow.. and then space out that number of items
im bad at those kind of setups. soo thats bout all i got to give 😅
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
1. Pick how many points you want total (example: 16).
2. Pick how big the square is (example: width = 10, height = 10).
3. Figure out how many points should go on each side of the square.
(take totalPoints ÷ 4).
4. Write down the four corners of the square.
5. For each side of the square:
- Start at one corner, end at the next corner.
- Evenly space the points between those two corners.
(search term: "linear interpolation between two points")
6. Collect all the points into a list or array.
``` @hallow acorn **edit**- *wait!, this is just for a perimeter
```fix
1. Pick how many points you want total (example: 16).
2. Decide if you want them arranged as a grid
(example: 4 × 4 points).
3. Pick how big the square is (width/height).
4. Figure out the spacing between each row and column.
(square size ÷ (gridCount - 1)).
5. For each row (y-axis):
For each column (x-axis):
Place a point at (x, y) position.
6. Collect all these points into a list or array.
``` ^ this would include the fill
dont need fill only an "outline" of points but thank you very much!
it'd basically be the same as making a 2D grid (since its a square Exactly the same) w/ nested loops
ahh then ya the top method would be great
thanks. ill grab some food and then ill look after how i implement that in code!
then u'd have ur list or array to pull the points from (w/ the index)
I have a slight UI issue, when I click the card in the right most panel(available cards), it adds a new instance of a card prefab to the middle.
The deck list is saved and stored and is accurate when it comes to how many times I clicked the test card.
The issue is the UI does not reflect this accurately, ex I clicked 14 cards the decklist has 14 instances but the UI only displays 11. Another issue is that when the refresh is ran, the cards sometimes appear in the wrong order(There should be enough space for 3 across, but it skips the third slot and jumps to slot 4 for some reason. It also just flat out removes a card when the logic should be add card.
Code: https://paste.mod.gg/ytojakcfidjt/0
first screenshot is 3 cards in current deck, second is when the fifth card is added.
A tool for sharing your source code with the world!
* * * *
* *
* *
* * * *
``` 🍀 goodluck
there are resources pinned
Oh ok thx
should I post this in UI-ux instead? i feel like it's a coding issue and the ui can't keep up
if I am completely new to coding and the Unity software should I install 6.2 or is there a better version to get started with?
no reason to start with an older version
and check out !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Use the same version that the course or tutorial you're following uses
I'm on the learn tab but it said to choose a version so I was unsure thanks for clearing that up
now that I have done the unity hub and editor tutorials what should I do next? should I look up c# tutorials or more unity ones?
you can keep doing the tutorials in unity learn i guess
at what point should I start learning the code?
doesn't unity learn teach code as well? i haven't used it myself but i've heard that it's a great resource to learn but if it doesnt then you can check the pins, there are a bunch of c# tutorials there so you should probably do those right away
It doesn't teach c# fundamentals
wait do the learn tutorials go from foundation to beginner?
okay then i'd check out the pins and learn the basics of c# right now
The old ones kinda did https://youtube.com/playlist?list=PLX2vGYjWbI0S9-X2Q021GUtolTqbUBB9B&si=WwGsv3KosQX9_CYw
And
https://youtube.com/playlist?list=PLX2vGYjWbI0S8YpPPKKvXZayCjkKj4bUP&si=yCrsm_VfR1fWaORu
Learn about programming for game development, from the very beginning with these easy to follow video tutorials. In partnership with Microsoft.
following up on this, is this something I should use wait functions on?
this is just an error in your code
the ui can definitely keep up
I have an advanced vehicle telementary running in a physics substep system and am updating the ui 100 times every fixed update
okay, then why is it specifically always erroring out on the 5th object?
no clue you haven't showed us any code or how you have your canvas set up in the scene.
oh wait you did show us code
let me go look my bad
so its skipping the 3rd slot and filling in slot 4, how is the 3rd slot being filled in the second screenshot? is it just adding the next card there instead next time you draw?
so basically clicks one and two work perfectly fine
on click 3, the slot that SHOULD be where the card goes is skipped
if
[]
is to represent the card
its like [1]. [2]. [skipped]
[3]
but then when I click it the 5th time it ends up like this:
[1] [2] [5]
[3] [4]
yes
show me the specific code where you are assigning what slot it goes to
I don't assign slots specifically, I just add it to a list and then the code instantiates a card prefab:
public void addCard(Card obj)
{
var found = availableCards.Find(card => card.cardName == obj.cardName);
Debug.Log($"[DeckEditorUI Found card: {found.cardName}");
selectedDeck.Add(found);
GameObject btn = Instantiate(cardButtonPrefab, selectedDeckPanel);
btn.GetComponent<CardUI>().SetupForDeckList(found);
btn.GetComponent<CardUI>().OnClick += removeCard;
btn.GetComponent<CardUI>().OnPointerHover += displayCard;
Debug.Log($"Current Deck Size: {selectedDeck.Count}");
refreshdecklistDisplay();
}
hey guys..i am a beginnr (REALLY BEGINNER) in C# and i have been struggling with basic player movement in unity 6.2 (the player is not moving no matter what i do) if someone is willing to help for free..DM me or just let me know
Screenshot the heigharchy before and after the slot is skipped
the heirarchy?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
like the parent/childs?
seems like you're just adding it as a child without enforcing any sort of order and expecting it to work
no-one's gonna be willing to help without knowing what you actually need lol
I thought the content size filter/grid layout would solve it, but I'll scvreen shot
It will if you got every set up right
but honestly I wouldn't suggest doing it that way
!ask hey guys..i am a beginnr (REALLY BEGINNER) in C# and i have been struggling with basic player movement in unity 6.2 (the player is not moving no matter what i do) if someone is willing to help for free..DM me or just let me know
this is before
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
here is after
that was embarrassing
put some effort into asking your question and you may get some help
no DMs
i already got some in texturing
i ask for it not str8 DM with no permission
You cannot Destroy a Transform component... they are essentials to gameobjects working properly, you delete the gameobject
just noticed lol thank you
From what im seeing your code should work and you dont have anything funky going on with the heigharchy id look at your canvas/grid settings next
that doesn't change anything
brother I think you need higher IQ before you attempt game dev
post your code
tell us the problem you're having
lemme just
before we continue, you have read #🌱┃start-here, right
specifically #🌱┃start-here message
@rich adder attached .gameObject after the child transform, my parent deleted itself with it
this is my current setup for the panel itself
teh whole thing isnt working
- post !code properly
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
- describe what isn't working
if it was working you wouldn't be here 😉 you gotta be more specific than that
could the content size filter + grid layout group be clashing?
I have a feeling that could be it
are you getting errors or warnings?
is something not responding?
is something responding, but not in the way you want it to?
show the line of code
doing .gameObject should not delete the parent if you properly referenced the child
[ContextMenu("Reset")]
private void DeleteChilds()
{
for(int i = 0; i < gameObject.transform.childCount; i++)
DestroyImmediate(gameObject.transform.GetChild(0).parent.gameObject);
}```
im not getting any errors..its just taht the whole code is not working properly..the player is not moving like its supposed to
wait.
on the same object? don't think they should
usually there'll be warnings telling you if they conflict
i did not put the .parent there
honestly yes but I will not be much help in troubleshooting that I have not used that much at all if ever.
i wonder why the parent is getting deleted lol
I mean ur doing GetChild(0).parent.gameObject
@rich adder
you'll have to ask #📲┃ui-ux if it's an issue with that
intellisense doesn't insert extra tokens, it just completes the token you're currently writing
you sure it wasn't intellicode?
yeah, I'll move there now, thank you all for the help!
maybe i dont know. ill just write my code in windows editor now
its ok the other day i spent like 45 minutes debugging why my audio stopped working randomly after restarting my pc only to find out later that the game view has a mute button that unity decided to enable all on its own.
no don't do that
ides exist for a reason
that hurts
just double check the code its suggesting before you press tab
its right a lot but its wrong often
also, why is this not deleting all children? cs [ContextMenu("Reset")] private void DeleteChilds() { for(int i = 0; i < gameObject.transform.childCount; i++) DestroyImmediate(gameObject.transform.GetChild(0).gameObject); }
ok yeah no that's intellicode not intellisense
ur not passing i?
did you even write this
this is basically the issue of modifying lists while iterating through them
ya also you need to do this in reverse
why?
or just change the condition
because of index it will skip the next element
imagine you have 4 children
first iteration, i = 0, 0 < 4, delete one, now childcount 3
second iteration, i = 1, 1 < 3, delete one, now childcount 2
third iteration, i = 2, 2 ≥ 2, so loop exits
you end up deleting 2 children
okay
the next item will have the current index
you don't need a for loop for this at all
you can just use a while (transform.childCount > 0) if you're just removing the first element
(also yeah, gameObject.transform is unnecessary, you can just use transform)
oh true
(well, technically not for this since it's not actually using the index)
