#💻┃code-beginner
1 messages · Page 468 of 1
Handling stack sizes was complex, someone suggested I chould use scriptable objects too. I have the whole thing working now, but it's fragile and a nightmare to debug, so it will probably get a re-design before done
Scene loads destroy objects, you can set them to not destroy on scene load but I forget the method off hand
When the scene reloads, stop the game with the pause button, change your inspector to debug mode and see if any reference is empty
My guess is the gun is not referenced to the player after reset
Seems you have a script that still has a reference to the old Gun from the previous scene. That object no longer exists
You're right, I misread that lol
how would i use the notdestroyonload function? sorry if this sounds dumb i only started a couple weeks ago 😅
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
This makes an object persist between scenes. It's probably not what you want actually, and your error likely stems from something that does have DDOL already holding on to references from the previous scene. I think more likely what you want is to have that script re-acquire references when the scene changes:
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html
ok, thanks
How do I make is so that the box I put code in is in c# on discord? I completely forgot
```cs
//code
```
I'm trying to get gravity to work properly while falling, when it jumps and falls it has the correct amount, however whenever you simply walk off a platform, you fall very quickly much more than if you jumped
my jump just adds a force with moveDirection.y = jumpForce, but im wondering if theres a better way, since in order for it to be responsive, i set the gravity and jump force higher
reset Y velocity while on ground
private void ApplyFinalMovements()
{
if(!characterController.isGrounded)
{
moveDirection.y -= gravity * Time.deltaTime;
}
if(willSlideOnSlopes && isSliding)
{
moveDirection += new Vector3(hitPointNormal.x, -hitPointNormal.y, hitPointNormal.z) * slopeSpeed;
}
characterController.Move(moveDirection * Time.deltaTime);
}
i realized that the moveDirection.Y glitches out on slopes and spheres
but im not sure how to rememdy that
glitches in what way
keep in mind character controllers have slopes built in
normally on a flat surface the move direction will be around -8 to -10, but after sliding down a sphere its all the way to -150
so you dont need to make them
well this is so you arent able to just jump on top of them
because the normal character controller allows you to jump over them
🤔
this makes it so you slide down and cant go up something you shouldnt
just move the character controller by Vector3.down via move method and you should be good
if you detect you are on a steep slope ofc
still in moveDirection?
you probably coud just make another move method and if on a steep slope move the character controller down
it should slide down
as long as you dont translate it
using translate will ignore collisions
wouldnt this stop the character from moving in any direction while sliding
do you want to move while sliding down?
one moment let me get a short video of what it does currently
note the moveDirection in the bottom right
how to goes up to insane values
this is with above code
that fixes the amount
however now I am able to jump over the slopes, because it resets the value while on the slope
when off steep slope
you need to check if you are on a steep slope
if not then reset it
oh I see what you mean
hmm it still seems to think im on the ground even when on the slope
are you checking the slope angle?
Ohh wait i see what I did wrong
i think it was a mistype, let me test it
Ok this works, i think the only thing I need to figure out now, is that if the slope goes right over an edge
because the -y movedirection will still rack up, but there wont be any ground to reset it
you can reset it while in air but you need to make gravity seperate then
or else you wont have gravity
actually, (im sure this is just me being dumb) do you know why this ramp lets me stand at the very bottom?
its probably something to do with my isSliding bool...
private bool isSliding
{
get
{
if(characterController.isGrounded && Physics.Raycast(transform.position, Vector3.down, out RaycastHit slopeHit, 2f))
{
hitPointNormal = slopeHit.normal;
return Vector3.Angle(hitPointNormal, Vector3.up) > characterController.slopeLimit;
}
else
{
return false;
}
}
}
Add debugs to see why specifically. First thing I'd check is the angle
Also something like this shouldnt be a property imo. Just check every update or fixed update. If you use isSliding twice in a frame then it's doing unnecessary work
Ah, I see what you mean about the unnecessary work, thats simple enough, as for the debugs, it seems that its not detecting anything, which is causing me to believe that because the raycast comes out from the center, at the very edge the hitbox is still on the slope, but the center is over the edge, im not sure how to fix that without an obscene amount of raycasts on all sides
its because you are using the built in charactercontroller.isgrounded I believe it detects the ground via the collider hit points
i could be wrong
so its detecting you are on ground but not on a slope
so I managed to solve the issue by removing deltaTime all together
void CheckDeceleration(ref Vector3 moveDir3D, Vector2 inputVector)
{
moveDirDecel.x = moveDir3D.x /6;
moveDirDecel.z = moveDir3D.z /6;
if (gravity_Check)
{
moveDir3D += ((inputVector.y * transform.forward) + (-inputVector.x * transform.right)) * 2 - moveDirDecel;
}
else
{
moveDir3D += ((inputVector.y * transform.forward) + (inputVector.x * transform.right)) * 2 - moveDirDecel;
}
Debug.Log(moveDir3D);
}
works somehow like a charm
then yes its most likely the charactercontroller.isgrounded detecting ground but your raycast isnt hitting anything. to fix this you can either make your own isgrounded system (really easy) or just make multiple raycasts to see if you are on a slope or not
or just orient your raycast to the slope
These are in 2 different scripts
and i keep getting NullReferenceException: Object reference not set to an instance of an object
how do i fix it?
set an instance of the object to the reference
is making your own isgrounded that simple? because just thinking about it i feel like the multiple raycases would be easier
its 1 line of code
double click the error.. find out what line causes the error...
you'll need to post the full error
depending on what you want
check the references within that line
- one of em is not assigned
- figure out a way to assign it
Line 16 in the OnCollisionEnter 2D
oh? is it just copying from the inbuilt is grounded, or is another raycast?
if you want a raycast system then do that, if you want a checksphere system then you can do that both are easy
well since u cropped the line numbers that information is only useful to you
This what you need? im not sure
we still dont know what line 16 is..
give us the full !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh its not in the screenshot lol
preferably in a paste site
oh
its _gameUIHandler
btw.. even w/o u posting the code
you have a private reference.. and no logic that assigns it
since its private i know its not assigned in the inspector.. so how is Unity supposed to know what instance of it, you are trying to use
you either need to
private void Awake(){
_gameUIHandler = some sort of logic to assign one;
}```
or use
`[SerializeField] private GameUIHandler _gameUIHandler;`
so you can assign it via the inspector
So im trying to use checksphere to replace isGrounded, and have this:
(Physics.CheckSphere(characterController.transform.position, characterController.radius, 10)
i know that the character controller position will have to be moved downward to the feet, but does everything else seem correct
public class CharacterManager : MonoBehaviour
{
[SerializeField] public int _playerHealth = 8;
private GameUIHandler _gameUIHandler;
public void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Enemy"))
{
_playerHealth--;
_gameUIHandler.ChangeHealthBarSprite();
}
}
}
public class GameUIHandler : MonoBehaviour
{
[SerializeField] private Sprite[] _healthBarSprites;
private Sprite _currentHealthBarSprite;
private CharacterManager _characterManager;
private int _playerHealth;
#region HealthBar Sprite
public void ChangeHealthBarSprite()
{
_playerHealth = _characterManager._playerHealth;
for (int i = 0; i < _healthBarSprites.Length; i++)
{
if (i == _playerHealth)
{
_currentHealthBarSprite = _healthBarSprites[i];
gameObject.GetComponent<SpriteRenderer>().sprite = _currentHealthBarSprite;
}
}
}
#endregion
oh i figured out how to post code lol
ik
you can just use a seperate gameobject instead of the character controller position
you probably would want a seperate float as well for the radius of the sphere
wouldnt I want the radius to be the same as the character controller, to see if it is the one touching anything?
you would get the same issue
if it was the same
so just make it a bit smaller
yea, you can just use an offset..
public Vector3 offsetForFeet = new Vector3(0,-1f,0);
(Physics.CheckSphere((characterController.transform.position + offsetForFeet), characterController.radius, 10)
or do as dec, sed and just use a different gameobject or something..
public Transform feetLocation;
i did the serialized field and all i can assign to it is the script and i still get the error
you dont assign a script to it..
you assign a Gameobject, within the scene, that has that script attached
ye thats what i ment
still got error
whats the error say now?
if ur still getting an error that means theres another null reference error somewhere
its probably this one now
its the _playerHealth = _characterManager._playerHealth
oh ye
things like floats, ints, vectors and stuff.. don't need assigned b/c they have default values
hey spawn camp
but if ur using custom scripts and stuff
they always have to be told what instance of it ur using
oh ok
or create a new one on the fly
so can i assign it in the inspector?
u can put [SerializeField] in front and yea
then assign it
^ thats the go to way of assigning things quickly
it doesn't always work.. for things like prefabs.. u cant assign stuff in the scene until they get spawned
soo u have to do things like GetComponent or Find.. or something lik ethat in the Awake() / Start() fuctions
oh ok
but for things u can. assign them in the inspector
do anyone got active ragdoll tutorial that you can recommend to me
website or video
how far up should I put the empty object? because I dont want it to touch the ground before my charachter controlelr does
just at the bottom of the character
make the Z coord 0 for the love of all thats precious
you adjust the variables in the inspector to get the desired effect you want
not the position
with zero its all the way over here
do u have it set to pivot?
just put it in the bottom middle of your character
considering I dont even know what that means, no
it doesnt need to be centered (to much)
oh yeah, its on pivot
if its set to center it shows the general center of all objects
ya, somethings not lined up correctly lol
heres on center and pivot
oh my
when u go to rotate stuff around its gonna break all to heck
lmao
oh boy
okay.. so far soo good.. b/c the position of the ROOT object doesnt really matter
zero them out
wait no
not the parent
why why.. is the center of this guy all jacked up?
heres everything(children) zeroed
ya, i didnt see ur Player Capsule...
change the center on the character controller to 0,something,0
its center should be 0,something,0
ohhh, my bad i misunderstood
u were giving me anxiety
lol
yea ur ground check should be just below the capsule
if you want to use they raycast method you can if needed
if u want to raycast from that position it should be a little above the edge
Might as well learn the check sphere while im here
10 is the layer for all my ground objects
then you are fine
rq how do you get the highlight of the char controller, and still able to move just the empty object
i have to unhighlight the controller whenever i want to move it
oh I see
yea, i use a capsule mesh renderer for my Graphics object
just make a capsule 3d object and remove the collider from it.
its pretty much a standard
(the CC already has a collider within it)
really helps when writting ur controller code..
so u dont have to keep clicking and seeing the gizmos
Ah i see, no collider in the graphics
just make sure its lined up to the controller's collider
nope.. just a renderer and a filter..
so i just created a 3D > Capsule and removed hte collider
cool
if you had a collider on the graphics then it would most likely fly in the air
which is not preferred
it would spaz out
and get all jittery and stuff.. it'd break my gun raycast, my groundcheck raycast, and alot of other stuff
my char controller is not a perfect capsule
thats fine
how do you change the radius of the graphics capsule
just from the inspector
collider inception
u can scale it using the transform
via transform
(since its just graphics)
oh im just being dumb, i was expecting a radius option but that makes sense
.25, some height, .25
the general rule is to keep the Root object scaled to 1,1,1 .. and anything physics... most people make the graphics as a child object..
that way u can scale it any way u want.. and it wont affect ur physics/ code
- Main GameObject (the root) [1,1,1]
- Graphics [anything you want]
i said scaled to 0.. but then it wouldnt exist 🤣 i meant scaled to 1
one final thing, its not quite matching up
its fine... w/ that weird tall shape it wont exactly
yessir!
this is what mine is set up as
i have zero clue why i have 2 groundchecks but oh well
Well we have no way of knowing what this is doing without further context
Like where it's being called from and how the move3d vector is used
Hello Anyone know how can i fix this error
You don't use Console in unity
accuracy * 50
i typically use 7...
I am just learning C# basics its not opened in unity
gives good detection w/o being too expensive
Ah, then go to the !cs server
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
alright
sorry Aethenosity wrong ping
yeah, i have never explored with the dynamic ground array stuff
i have never been good with arrays
they scare me
I was confused haha. No prob
arrays are sooo ez dec
bet
i probably will, i know a lot of times where an array would come in handy
just used one, and a forloop to draw a gizmo circle
altho.. i can probably do that w/o the array.. and just add to the values in the loop
but loops scare me
Hey guys. I'm trying to set up input with the new input system. In my input actions file/window, there is no option for the spacebar, or any other keyboard inputs. Specifically how do I set up the spacebar for my game?
This video shows that the input actions doesn't even listen for the keyboard and also that I can't type it in. Maybe im typing it wrong though.
nothing from the keyboard
weird
you should def have a Keyboard dropdown in there
lol look at u.. problem solving things u never even heard of
ya, get out from under ur rock
i havent seen it before lmao
no I did try that and it didnt work
tried it again right now, thats not wat its for
its basically a must-have if u want to do things like Dynamic Key-binds
for the menu's
or 2 player games or w/e
Does ontriggerenter effect still works if both object istrigger is enabled
So now the sliding isnt working at all, its not detecting that its on a slope at all
heres the check sphere
Physics.CheckSphere(groundCheck.transform.position, characterController.radius - 0.05f, 10)
also isgrounded = Physics.CheckSphere(groundCheck.transform.position, Float, 10)
well right now I just have the whole checksphere in place of where isGrounded normally goes
while testing
It doesnt work?
I tried it it doesnt work
still use a float
on it boss
you cant use Keyboard for the setup u have
Value Vector2
My Axis-Type Keybinds are under an action using 2D Vector DigitalNormalized
let me try that. I was just about to delete my project and start again
ty
So i tried setting the groundCheckRadius to 0.1,0.2,...0.6 and it didnt detect at all in any
Physics.CheckSphere(groundCheck.transform.position, groundCheckRadius, 10)
its probably gonna be 2.3 or 3.2
its not too bad.. u can set up action maps and stuff.. and then it Generates a C# file for you.. with all the Callbacks and stuff it needs
wouldnt that go past the radius of the char controller though?
its basically Events being called when stuff happens (instead of polling [every frame in update]) for example
from what i tried it doesnt
but 0.6 and 0.2 is very small
just adjust it till you get a hit
tried all ints from 2-10 none are sliding
seems interesting
is it detecting ground?
nope
layering wrong?
@rocky canyon you fixed by issue tysm. works like a charm
shouldnt be, its 10 in check sphere and the ramp is on layer ten
Yes
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
(Stolen from digiholic)
try changing the 10 to a layermask
and do what spawn said
layermasks look like this correct?:
layerMask:10
never used them before
also what did spawn say, that was with the raycasts instead of checksphere?
No, a layermask would not look like that at all
I recommend just making a layermask variable and changing it in the inspector btw. That is the easiest.
Otherwise if you want layer 10, it would be 1 << 10
You need to use a bitwise operation
A bitmask (layermask) is like a list of bits. Each a flag
private void OnDrawGizmos()
{
// Set the color for the Gizmo
Gizmos.color = Color.yellow;
// Draw a wire sphere with the radius specified by groundCheckRadius
Gizmos.DrawWireSphere(groundCheck.transform.position, groundCheckRadius);
}
``` i said u can use OnDrawGizmo's to help u visualize
to be fair, it might, if it's layers 1 and 3 😄
public LayerMask layer
Physics.CheckSphere(groundCheck.transform.position, Float, layer)
or do what Aethenosity said
OK perfect, its sliding now,
also preferrably a [seriliazed] private layermask
cool! :).. i actually didn't know if it would or not... I just have it setup from a long time ago.. and i just copy and paste it around to create new ones
however it still has the same issue with isGrounded :/ im stuck at the edge of the ramp
That would be layer 2. It would only be one layer, as there is only one bit set to 1
lower it till you fall off
okay
they do start at 0, yes... and 10 is 2 layers 1010... but anyway, was just jokingly being too pedantic 😛
any lower and it doesnt slide at all
what does the ramp collider look like
and do what spawn said
ok one minute
here (sorry for the ping)
Oh wait
I see what you mean now. Yes I get it. My bad
It would "convert" it to what you said
and you don't need to Call OnDrawGizmos() from update or anything..
its one of those magic unity methods.. that just work on its own
yeah its doing that rightnow and my console is overflowing with errors lol
but it still shows it
sooo its in the right location it seems
'Default parameter value for 'rotation' must be a compile-time constant'
private void SpawnObject(GameObject obj, Vector3 pos, float scale = 1, Quaternion rotation = Quaternion.identity){
How can I fix that please?
Set it in Awake or Start
where do you assign it? that's the issue . . .
As a methoed parameter default value
call it myRotation or summin
.identity is a property, you cannot use it as a method param default value
did you guys know that if you call deltaTime in fixedUpdate, it calls fixedDeltaTime instead?
as spawn mentioned, it needs to be default as it's a property, not a constant . . .
Yep. Pretty common knowledge around here
Ok thanks, but so how do I set the rotation default value to 0,0,0?
well it took me 3 hours to figure that out actually, was breaking a mechanic in my game
Ok thanks
yup, that's how it works . . .
void SpawnObject(GameObject obj, Vector3 pos, float scale = 1) => SpawnObject(obj, pos, Quaterion.identity, scale);
void SpawnObject(GameObject obj, Vector3 pos, Quaternion rotation, float scale = 1) {}
A default quaternion is invalid
🪄 wooOOoOooo
imo it should just call for the one I'm interested in
Probably wouldn't be the first place you would look for your issue, but the docs do explicitly say that for deltaTime
https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
What does this mean?
how so?
well I figured it out through trial and error eventually
It looks like it's valid cause I just did Quaternion rotation = default and now it works fine
thanks anyway
A default quaternion is not valid.
i think he means if he calls time.deltaTime in fixed.. he still wants time.deltaTime.. not fixedDeltaTime
But did you USE it? That is the issue nomnom is talking about
but idk ¯_(ツ)_/¯
Yes
Why? That would be awful
lol.. ik im just guessing thats what he means tho
In instantiate or something? Not as the parameter
Yes
Ah
No
You're right, I didn't use it lol
that's a bit weird, but you can store deltaTime in a variable and use that variable in FixedUpdate . . .
just have an overload that will assign it for you
[SerializeField] RenderTextureMakerCamera renderTextureMakerCamera;
[SerializeField] new Renderer renderer;
void Start(){
PrefabsReferences prefabsReferences = WorldManager.instance.worldsPrefabsReferences[renderTextureMakerCamera.id];
renderer.materials[0].color = prefabsReferences.planeColor;
SpawnObject(prefabsReferences.tree, new Vector3(0f,0f,0.3f), 0.025f);
}
private void SpawnObject(GameObject obj, Vector3 pos, float scale = 1, Quaternion rotation = default){
GameObject prefab = Instantiate(obj, pos, rotation);
prefab.transform.SetParent(this.transform, false);
prefab.transform.localScale = new Vector3(scale,scale,scale);
}
This is my code
and it worked fine
And I did use the quaternion defualt to set the rotation of the prefab in Instantiate()
soo if u exclude rotation in ur method params it spawns it at Quaternion.Identity?
today, im learnin!
Not anymore, as this wasn't working and was throwing errors, now it's set to default
so basically I got a cube that pushes my player away, the player movement is in update and it decelerates over time
but the raycast that detects if the player collided happens in fixed update.
My player accelerates faster with more FPS, but also decelerates faster and so it keeps a constant speed across all framerates
But I had to divide the speed that the cube uses to push my player away using Time.DeltaTime because the deceleration speed of faster framerates is bigger and so the value of acceleration it gives must be bigger just like in movement.
And so took me 3 hours to figure out that the reason it wasn't working was because physics use fixedDeltaUpdate and so it converted it to that. In the end I just stored the actual deltaUpdate in a variable and applied it there and now it works
its weird, its like its randomly deciding to stop at the edge
theres not a collider on ur empty foot object is there??
nope
like if I can specify fixedDeltaUpdate and deltaUpdate at the same time, it should just call for the one I want, not the one it thinks I want
its probably just not enough force to push u up that steep of a slope
i'd see what happens on a shallower slope
actually its because you are using a raycast to detect if you are on a steep slope
ahhh
But if you are using FixedUpdate, then deltaTime would be irrelevant and should definitely not be used
best use a sphere raycast
is there a way to get the info like a raycast hit, from a sphere check
well there it is
for this aplication
thank you
lol
well I want to detect player collision in fixedUpdate to detect it only once and apply speed in Update basically, but I use the function that applies speed in the detection function
Hm I wonder if instantiate does an invalid quaternion check then in C++ land before using it 🤔
you should find out and let us know
Is there a channel for questions about textures rendering issues? Cause I can't find one
Sir I do not have source code access
Ok thanks
ohh thats right
Gotta have the big bucks for that 
- why apply speed in update. FixedUpdate would be better for that
- what does that have to do with deltaTime. Use a bool to only detect once
i was waiting for someones response
🤔
ok so once I detect collision, I call for a function that calculates the speed and gives it back to the player.
The problem is that I call the function from from the collision detection function that happens in fixedUpdate
My player runs physics in Update and that's because when I tried making it move in fixed update it was very laggy for some reason and I gave up. And now I got so much code built up upon it that I'd rather work around it instead
I need delta time in fixed update to account for the player moving in update
so I just created a variable that stores it locally instead
It wasn't laggy in fixed update, you just saw it without any interpolation
I don't even know what that means
interpolation.. it guesses the inbetweens and gives u a smooth render
Fixed update runs on a fixed interval, you saw it only on that interval, instead of smoothed out
ah I see
You can see this if you add a rigidbody to a cube with interpolation disabled, see how it stutters, then enable interpolation, and it is smooth
can you enable interpolation for the default character controller?
Nah that doesn't use physics itself
an example
well I use the character controller for the player movement
yes I understand what you mean, thank you
np, i just like filling up my hd w/ video 😅
CC is fine in Update since it is a kinematic body (aka not on the physics tick). I've done checks in Fixed to then use in Update for various things, but update is fine for a CC.
tbh, im amazed w/ myself.. how was able to get that little tilt when i go back and forth
If you are using the CC, why use FixedUpdate?
Why not use OnCharacterCollideraHit or OnTriggerEnter for collisions
I got like 200gb of unity tutorials downloaded for no reason at all
👀 im better than i thought i was
for when the internet dies ofc
because I run raycasts to detect collision
Yes? Those should be in update
what
or vice versa
but when I run them in update they happen like 2-3 times per frame
So what?
I only need them once
That makes no sense
Then do a bool to only do them once. In update
remind me what does CC mean
CharacterController
ah
CC / RB carrot cake, and red balloons
why is there fixed update being used again?
If you want checks that are from physics, and you don't want to over-check them, you can always just check them in Fixed, save to a variable, then read from Update to check/reset it.
Or just keep them in Update. Whatever works for what you want/need.
thanks digi
No idea. I say it should not be at all here
basically when my player hits a wall that has a script, it runs the script only once and that's about it.
I used fixed update because for some reason it ran it like 3 times in update
if ur relying on CC it has its own collisions 🤔
Well yeah, update runs a bunch. Make a bool to only care about it once
how would you check if a frame as passed with a bool?
lol.. the next time it runs
but.. u could use a timer/ or a coroutine/ or a custom tick rate.. to control how often things happen..
or throw it in fixed update.. lol
but yea.. when something happens u flick the bool...
exactly one frame will happen befor its considered again.. but then it'd be a different state.. soo 1 frame has run
I think we are talking past each other. You want to not hit walls. Ok, so check every update if you are moving towards the wall. If you are hitting the wall, don't move that way. Not sure why the number of times it is called even matters. But you could set some bool when you hit the thing, and reverse it when you don't
Maybe show your code. Because your descriptions are confusing me a lot.
ive been confused.. im still trying to put it all together
how do you upload large codes again?
the player shouldn't accelerate faster with more FPS, that is incorrect and means you're frame-dependent instead of frame-independent . . .
Gdl.space
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hey so i want to check if the gameobject is on a certain layer how can i achieve this?
what have you searched so far?
that's an easy google answer . . .
maybe this can help us @summer stump
lol.. just for some context while reading the code
if(this.gameObject.layer = "enemy")
im dumb
okay, but have you searched that question online yet? i only ask because that's a simple google search. also, you should check what gameObject.layer returns . . .
Okay, what happens if you try that
use @amber spruceCompareTag(string); sorry meant to ping
i forgot in this case i want to do 2 equals
oh its a layer... 🤦♂️. sorry i need discord scaling
ye
you probably mentioned it, but how are you moving the object? it should be framerate independent and not move faster/slower depending on the FPS. using deltaTime or fixedDeltaTime shouldn't mess up anything in FixedUpdate . . .
ok here's the entire characterMovement code, it's not very modular, poorly written, and has a lot of other stuff as well but it works
ohh deer
wait
i think i figured it out i just cant use the layer name i gotta use the number for it
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you could use a layermask.. but yea name works too
ok I think it works now
You are doing three separate raycasts in the check collision method....
Then omg five in the other. Ok, I guess those ones make sense. They are pointing different ways
well I need to check up, down, and then I also need to check if the cube is at my feet or my face in the direction that I'm walking towards
weird code lol..
cool cool...
https://gyazo.com/d53a6bc1cdee2e467ed5dbd7180d5547
Is the order htey are loaded deterministic? or could it be random?
sounds like my character controller..
8 months
ur player moves in update..
yet u only jump in fixed?
the Y direction is completely separate from the other 2
it goes like this https://docs.unity3d.com/Manual/ExecutionOrder.html
yes... theres no other way, esp not random
not sure else u could mean by loaded.. unless ur talking initialization type stuff
you should see the portal script I made, bet no 1 would understand it
ya, spatially.. but logically id reckon they'd both be as equals
are you talking about the scripts in the Script Execution Order?
if u let me move 60 times in a second during update.. but u only allow me to jump every 50.. it wouldnt feel balanced
but im just nitpicking.. its not like its broken or anything so ignor me lol
basically I handle gravity and jumping together, and moving with the deceleration on the other 2, I got 2 different forces that deal with how the player stops and they never intersect
ah, makes sense.. mine i do that kinda too.. but i add all my forces up before each move frame
b/c my gravity is interpolation during the update
also w/ my grounded/slope checks
I mean like if you have script A and script B and have set nothing to override the order. It says in the order loaded, but don't see anything that states how one is loaded before the other
that is random..unless u specify
I updated all the isGrounded to the customIsGrounded, and im getting this weird bug when in the top corners of platforms
thats why singletons and initializations of those can error.. unless u have one awake b4 the others or 1 start b4 the others
idk, it was tuff for me to figure out, especially when I had to make a script that inverts gravity
and then you'll have a race condition.. its best to use
- Awake to initialize self
- Start to initialize/grab components or w/e from others
see I have the exact same issue with my game, the way I solved it was that I made the character controller SO SLIM that it's barely visible, probably not the smartest solution
my character controller is slimmer than normal, but i wouldnt say you cant see it
That only applies to the scripts added in the Script Execution Order window. You are specifically on the page that talks about using the Script Execution Order settings . . .
well I may exaggerating
my radius is 0.25
very slim nonetheless
i see
I think that that's just how the character interacts with slopes edges I guess
actually I figured this late and never used it but there's a better character controller in the asset store made by unity if I'm not mistaken
for free
whats different about it?
idk let me look it up again
alr thank you
a lot
it has gravity, uses cinemachine
I see android joysticks on some images
ah yes those are included
neat, but il stick with this custom 'basic' one for now, as this is just me learning unity
here's a link to it https://assetstore.unity.com/packages/essentials/starter-assets-character-controllers-urp-267961
if it helps with anything
yeah I did the same, I needed my own custom logic anyways
wait are you unable to add custom logic to the advanced one?
or just because you already wrote it
well, yeah I have already written it by then, but even if I hadn't I feel like it's a lot harder to modify someone's script than it is making your own
ofc ofc
how do i instantiate smth as a child of a specific gameobject
look at the available overloads for Instantiate
Instantiate has a parent parameter you can set. Or you can set it afterwards with .SetParent(...) on the transform of the object you've instantiated.
I am making a turn based rpg and am currently stuck on an issue where the enemy I touch doesnt delete in the overworld scene after I finish a battle. Im pretty new to unity and my only thought so far has just been to destroy the enemy object when its touched by the player but when I destroy it the enemy it reapears in the overworld when the battle is over. Any ideas?
you have to track the state of your enemy , if it was destroyed in battle scene it should not reappear
looks like a problem w/ the way ur gravity is affecting the capsule + a spamming of grounded/isn't grounded
yeah it glitches only when jumping on a platform near the very edge
https://paste.myst.rs/rl9kfxze i was gonna say, urs looks pretty complex.. lot of that can be simplified to get the almost exact same feel.. mine uses cinemachine as well
a powerful website for storing and sharing text and code snippets. completely free and open source.
you can check out how my flow worked atleast.. (just commenting back from when i mentioned your jump)
but if it aint broke dont fix it.. ya know.
ya, b/c the capsule was not grounded.. then it is grounded for just a second.. and then slips off the edge, then its not grounded.. but before it call fall.. ur spherecaster says it is... and then it cycles
what happens if u made ur spherecast just a little smaller than the player
it is by 0.01
ah, nvm that may make it worse
ohh its that dang gizmo thats throwing me off
u should remove that if its not like that anymore
the gizmo is the custom is grounded radius
or comment it out // unless ur still using it
shouldnt i be using it because this is a isgrounded issue
when that happens i bet ur isGrounded is flickering on and off
whats ur groundcheck code look like
one sec
thats a crazy list of variables lol
still.. the white ones arent 😅
private bool IsSliding
{
get
{
CustomIsGrounded = Physics.CheckSphere(groundCheck.transform.position, groundCheckRadius, groundLayerMask);
if(CustomIsGrounded && Physics.SphereCast(transform.position, groundCheckRadius, Vector3.down, out RaycastHit slopeHit, 2f))
{
hitPointNormal = slopeHit.normal;
return Vector3.Angle(hitPointNormal, Vector3.up) > characterController.slopeLimit;
}
else
{
return false;
}
}
}
put the customIsGrounded in here just to show what it is
just tried to set all other customIsGroundeds back to regular charcontroller.isGrounded still didnt work
hmm.. u could buff up ur regular ground detection...
or you could use a cooldown buffer or something to the isSliding.. soo once u start sliding you can't begin sliding for a few milliseconds or w/e.. soo that way once that isSliding starts to flicker like it does.. ud be able to override it and walk up just enough to where the next time the issliding check goes u wouldnt be sliding..
then finally.. you could use a more complex ground check.. or additional raycasts.. to check if ur up on the ledge
it looks like one of those really hard to solve unless ur right in front of it, tinkering w/ it urself.. kinda problems
whats the problem? i came in a little late, did the spherecast not work?
ah
the spherecast could be hitting the wall reading 90deg and thinking its a slope
but like spawn said, you can use a cooldown to be able to slide. like
if(Wassliding){
//some corountine to wait a certain time then allow sliding again
}
Hey, everyone! I'm having some real trouble with an array. I've tried a few things but I still end up stuck with this one issue I can't solve.
What I'm trying to do:
I have buttons set into an array. I have a reference to a counter that goes up by 1.
When the counter has a value that's equal to a button's element number, that button should change animation states.
What the problem is:
Only the first button in the array is being effected.
{
public Button[] buttons;
public PersistentCounter counter;
private string currentState;
public const string LEVEL_BUTTON_ACTIVE = "Level_Button_Active";
public const string LEVEL_BUTTON_UNLOCKING = "Level_Button_Unlocking";
public const string LEVEL_BUTTON_IDLE = "Level_Button_Idle";
void Start()
{
CheckButtonsAgainstCounter();
}
public void CheckButtonsAgainstCounter()
{
int counterValue = counter.GetCounterAmount();
for (int i = 0; i < buttons.Length; i++)
{
Animator buttonAnimator = buttons[i].GetComponent<Animator>();
if (buttonAnimator != null)
{
if (i <= counterValue)
{
ChangeAnimationState(buttonAnimator, LEVEL_BUTTON_UNLOCKING);
}
}
}
}
void ChangeAnimationState(Animator animator, string newState)
{
// Stop the same animation from interrupting itself
if (currentState == newState) return;
// Play the animation
animator.Play(newState);
// Reassign the current state
currentState = newState;
}
}```
sorry was away for a minute, this would stop my character from sliding on a normal slope im pretty sure
if(willSlideOnSlopes && isSliding)
{
moveDirection += new Vector3(hitPointNormal.x, -hitPointNormal.y, hitPointNormal.z) * slopeSpeed;
}
heres the part in my ApplyFinalMovements();
it shouldnt, if you were sliding on a slope but now you are not do a cooldown
but if its starting to slide on the corner wouldnt it continue to start to slide?
no
actually now that im thinking about it, it would probably do the slide once and then act normally
not just act normally
you can try it, but it might do this so
sorry was starting to work on the coroutine, i think it would do the first slide movement then stop you on the ramp not sliding until to stalltime completes, then would do that one movement then go back to standing still
yeah I see what you mean
you could just make the spherecast not detect 90deg angles
that would work
or an angle over your steep angle
if(angle >= 90){
//dont slide
}
//or
if(angle >= steepslopeangle && !angle >= 90){
//slide
}
something like that would work
no matter how u do it.. basically it comes down to prioritizing 1 of 2 things..
either u climb up on the ledge.. or u fall of it
i have one of each lol.. (my character controller always grabs the ledge like a champ (b/c he only has 1 raycast).. the other i paid for.. and he tends to fall off of edges.. (it uses an array of raycasts in a circle)
one has a better detector.. it can know when ur not techanically on the ledge
and it yeets u down
ya, i agree w/ this..
i think ur slope detection shouldnt detect over soo steep an angle
Sorry, my discord was breaking, and wasnt letting me send any messages
like at all
right now it just uses the character controller slope limit
Vector3.Angle(hitPointNormal, Vector3.up) > characterController.slopeLimit;
how something like this
if(!(Vector3.Angle(hitPointNormal, Vector3.up) >= 90))
{
hitPointNormal = slopeHit.normal;
return Vector3.Angle(hitPointNormal, Vector3.up) > characterController.slopeLimit;
}
~~wouldnt it be something like? ~~
for (int i = 0; i < buttons.Length; i++)
{
Animator buttonAnimator = buttons[i].GetComponent<Animator>();
string buttonState = LEVEL_BUTTON_IDLE; // (OR LEVEL_BUTTON_ACTIVE)
if (buttonAnimator != null)
{
if (i <= counterValue)
{
buttonState = LEVEL_BUTTON_UNLOCKING;
}
ChangeAnimationState(buttonAnimator, buttonState);
}```
so u can keep all the buttons idle except for the one ur changing? edit: nvm, misread the problem
So i added a debug variable to show me what the angle in, and it doesnt even seem to get to 90 or 0 at all when jittering on the corner of the platform
The buttons are used for a level selector. They're supposed to change animation states sequentially based on the counter value
you and me both
you should put Vector3.Angle(hitPointNormal, Vector3.up) > characterController.slopeLimit;
asAngle = Vector3.Angle(hitPointNormal, Vector3.up)
then return return hitPointNormal.normal != Vector3.up; for readability
this is mine
private bool OnSlope()
{
if (Physics.Raycast(transform.position, Vector3.down, out Slopehit, Slopehitrange * 1.5f))
{
//calulates angle between vector3.up and slopehit.normal to get the angle of the slope
angle = Vector3.Angle(Vector3.up, Slopehit.normal);
if (angle < 40)
slopehitrangefloat = Slopehitrange / slopediv;
else if (angle > 40)
slopehitrangefloat = Slopehitrange;
}
if (Physics.Raycast(transform.position, Vector3.down, out Slopehit, slopehitrangefloat))
{
//returns false if not on slope (basically means to not use slope code)
return Slopehit.normal != Vector3.up;
}
return false;
}
this is modified so ignore the extra stuff
you would only need 1 raycast
and then just do what I said here
and you should be good
Hey guys. I'm making a sort of top down 2d game, and I want the player to rotate and look towards the mouse at all times. This is my code so far, and this is what it is producing. Any suggestions?
`void OnLook()
{
Vector3 screenPosition = Mouse.current.position.ReadValue();
screenPosition.z = Camera.main.ScreenToWorldPoint(transform.position).z;
mousePos = Camera.main.ScreenToWorldPoint(screenPosition);
mousePos.z = 0f;
Vector3 directionVector = (mousePos - transform.position).normalized;
float rotationDelta = Vector3.SignedAngle(Vector3.right, directionVector, Vector3.forward);
transform.rotation = Quaternion.Euler(0f, 0f, transform.eulerAngles.z + rotationDelta);
}`
nevermind I guess the video is in 2 fps
so you guys cant see anyway
try and record it again, it was working before you pressed play
I guess your OBS is being weird but
let me close some programs
I have a weak pc
yeah i cant do anything more
just a performance issue
you probably shouldnt use OBS if you have weak PC
whats the alternative
i can't tell but could it be because its the transform.right thats pointing at the mouse and not the up
wdym the up? and I feel like that line is the issue myself
u see how the right (the red axis points at the mouse) even tho i want the transform.up (axis) to point at the mouse.
ur calculating from vector3.right to the mouse position
but u keep adding that to the rotation each time..
(thats why it keeps spinning around in one direction)
do transform.rotation = Quaternion.Euler(0f, 0f, rotationDelta); instead (i think)
just FYI, the atan2 call and stuff is unnecessary. you can just assign the transform.up or transform.right to the direction from the object to the mouse's world position
ahh yes, changing it now
lol, i always forget thats the easiest way
update, looks like it's working now but inverted.
bro what are you using to record 😭 🤣
get OBS or geforce experience or windows recording
I have OBS but it lags too much. That software works fine
literally has ads on it 💀 but alright, everyone chooses what they want i guess
if an object like a tree has an "object" script attached to it and I am creating a procedural dungeon, should that be a prefab or part of a tilmap?? Maybe its a stupid question but I am confused
should what be a prefab, the tree? yeah
usually anything that you will use more than once / in other scenes can be a Prefab
it has the "breakable" logic on it
okay, thanks, I´ve got another question then, how could it be instantiated if the map is procedural and randomly generated?
i assume the code for that would have a place where you would instantiate it
not sure how procedural works exactly though
how do I do that?
just randomly created terrain but I would like to know how to instantiate those trees once the map is created
aye, did it w/o atan2.. (took me a minute.. as i forgot about the camera's Z position mattered)..
void Update()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = transform.position.z;
Vector3 direction = mousePosition - transform.position;
transform.up = direction.normalized;
}```
exactly like i said. use the direction as either the transform.up or transform.right depending on the direction the object faces at 0 rotation.
it's inverted though
then . . . switch it . . .
if you used that code that spawn just gave you and it is facing the opposite direction, then your object points down when not rotated which is not ideal. but you can just negate the direction
No i think that the rotation is being applied inverted. not the sprite
that's what I meant to say
what direction does the sprite point when it is at 0 rotation
it points up. its a triangle
show your code then, sounds like you maybe have your direction calculation backwards
then transform.up = direction should be pointing at target
did u do transform.pos - mousePosition or mousePosition - transform.pos
I tried both. The difference is that one points the object down and the other points it up.
my code is https://gdl.space/zavahusila.cs
well if ur using Look now, ur mousePos isn't being updated
not unless OnLook is being run from somewhere
np
OnLook is run every time I move the cursor
screenPosition.z = Camera.main.ScreenToWorldPoint(transform.position).z;
I tried putting it in update but it has the same effect
can you explain the thought process behind this line
lol, i see where ur going with this..
the screen to world point values should be relative to the position of the player. If I do something like camera.nearclipplane, the values are all too small relative to the player.
wouldnt RotateTowards work? as long as you give the correct vector2 values in the vector3 and just make the other one like 1 or 0 or something.
im thunkin rn
its not that thats broken
its the way he trys to integrate the z value into all of it
that doesn't make any sense with regards to the line i am asking about. you are using a world position as a screen position, then getting the world position from that screen position and gettings its z axis for some unknown reason. that line is wholly unnecessary and makes absolutely no sense
screen position is used by Camera.main.ScreenToWorldPoint(screenPosition) in the very next line
now that you point it out I should definitely just use screenposition.z = transform.position.z
but I still need that line
when u Debug directionVector just before u assign it as transform.up
it's Z coord should match ur gameobjects Z coord
do not set the z on that object. use transform.position.z for the z axis of mousePos
if you are using an orthographic camera (which i would assume you are if you're doing 2d) then the position returned by ScreenToWorldPoint when the Z axis is 0 will be the correct position but with the camera's Z axis value in the Z axis of the returned Vector3. you do not need that first assignment to the z axis of the screenPosition object, you only need to assign to the z on mousePos
like this?
mousePos = Camera.main.ScreenToWorldPoint(new Vector3(screenPosition.x, screenPosition.y, transform.position.z));
you said use transform.position.z for the z axis of mousePos
void OnLook()
{
Vector3 screenPosition = Mouse.current.position.ReadValue();
mousePos = Camera.main.ScreenToWorldPoint(screenPosition);
mousePos.z = transform.position.z;
} ```
like this ^ fam
and you are not doing that in the code you posted, you're still doing the same exact thing you were before by using it as the z axis of the screenPosition variable
u confused urself, and us w/ the two methods, and the strange screenPosition.z thing
yep I didn't understand correctly, thanks for your help. It's working flawlessly now.
thank you spawn camp games as well
I was calculating the world position using the wrong z value
simply yea. 👍 ultimately its gotta look at its own Z coord or else it tilts to and away from the camera
i just fixed up my own look at mouse script now lol. i've always used atan2 until i seen boxfriends comment
i guess its still useful in other departments
Does somebody know how to place (trees,rocks, bushes, etc... ) randomly in an already generated (procedural) terrain in Unity 2D?
so i am trying to move the tile 1 tile size down if there are no tiles below and if it is still in camera view
i have 2 issues
- cell size is bigger than the actual tile size for some reason,
- how i can get cell size in int and not float? so i can avoid the vector being 1.0000001
is it a problem is i put too many regions in a script? i keep getting lost in my own code when i'm trying to work on one specific thing
if you get lost in your code then it's probably too long. not sure i've heard that before . . .
i probably should organize it lol
each script should only handle one behaviour . . .
The two phases of using regions:
"Wow these will make it easier to hide stuff I don't need to see!"
"Wow I hate clicking so much more where is my code aaaaaaa-"
it's a player movement script, and it has movement, jump, walljump, different kind of movement while in the air, ground check, gravity, wall checks, and i'm planning to add dash and ground slams
i've seen people use #region — including myself — to section off or organize code, so it's not terrible . . .
the more i wrote that the more i'm convincing myself to separate it in scripts
ground slam sounds like an attack, not a movement. all of these can (and should) be a separate script, but that involves a refactor your not willing to do (at this time) . . .
i just felt it was more convenient since they share some variables and i dont want my inspector to be a pile of scripts
this makes it easier to add scripts onto GameObjects to build a player, enemy, or npc. what if you want movement but no jumping?
also, didnt seem like things i'd re-use for other gameobjects, just the player
that is a good point
it's a lot easier to deactivate a certain mechanic
great for testing and bug fixing as well. only turn on the component you want to check . . .
alright, you convinced me to spend the next half hour doing this
i just made a separate move and rotate script myself, for a player . . .
👀

ransomink surely not drunk? 😛
or another example: i have a gun with separate scripts for shoot, reload, fire mode. that way, i can choose what functionality i want for each gun, even automated turrets . . .
I guess this goes along well when working with a designer that likes getting hands-on and experimenting in Unity
i first used it in the longest script i've ever written: the Timer class i made into a package. to be honest, it's only that long because i created summaries for every single field, constructor, property, and method . . .
honestly, it's pretty cool to make all the functionality in an SO and drag-n-drop them into their separate mechanics (components) to change the behaviour . . .
@grand badger here, you can see why there are so many lines. i made summaries so anyone using it will understand what everything does, as if i was releasing a package (asset) . . .
i done so many one-off projects or helped with certain mechanics, i've never really finished any concrete system or mechanic myself. now i have mind map of every system i'm working on and where i'm at to try and finish something . . .
So is there a way to get tile size that is correct?
Or cell size is correct and I am doing math wrong in the scene perhaps?
And also
Is my iteration over tiles ok?
just cast to (int)
usually you'll want to be working with floats all along for more precise math, then use Vector3Int.RoundToInt(myVector3)
I mean I am moving constant distance each time
(Cell size)
So I assumed the int would be better
var y = 1.6f / list.Count;
foreach(GameObject obj in list)
{
obj.transform.position += new Vector3(0, y, 0);
yield return new WaitForSeconds(0.2f);
}
``` if the y position starts at `0.4`, should this end at `2`? because it ends at 3.6 for some reason
y is 0.08 so that x 20 would be 1.6, so not sure why this doesnt work
we don't know what Count is . . .
its 20, but the same result with 10
i want it to increase by 1.6 no matter what the count is basically
I try to keep my files within 70 lines (which is about how many one screen will fit), so I'm usually not considering regions.
A single case I've justified the use of #region is when I actually had code I wanted to hide because its existence is implied.. I can't remember the use-case now though lol.
which is what happens except it ends at 3.6 instead of 2 for Y position
if ur working in grids, and cells ints are better imo
code is leading us to think obj is different on each iteration, so if each object starts at 0.4, it should end at 0.4 + 1.6f / list.Count.
if list.Count is 1, then yeah it should end at 2 if the obj is at 0.4
well im increasing obj each time if thats what you mean
thats inside the foreach statement
the code is saying that you're increasing y of a bunch of objs
oh, all of my files are small; no more than 100. this was a Timer class that handled everything and expanded after requests . . .
no sorry i think i did it wrong.
im looping through a list but im changing the position of a different object.
so its not obj.transform.position its somethingelse.transform.position
classic 🙂
yeah that's totally not what you're doing here 😛
yeah thats my mistake on writing it in discord
i thought we were witnessing some type of brain teaser
but the one im increasing position of is at 0.4 and i want to increase it by 1.6
to make the total of 2
show actual code that has the issue?
yeah, thats why i am trying to have all movement in ints
need to make sure to run ur move logic in steps then
private IEnumerator Spin()
{
var y = 1.6f / weapons.Count;
foreach(GameObject weapon in weapons)
{
Debug.Log(y);
baseWeapon.transform.position += new Vector3(0, y, 0);
yield return new WaitForSeconds(0.2f);
}
yield return null;
}
wdym in steps?
well i just mean.. its not ur typical.. bunch of move calls in update()
im just making my way back up to this
yeah, you're calling the Spin coroutine twice
your code needs work though 😛 still badly written
is that what the null does? or how does it call twice
whats bad about it?
it's misleading again -- you're not using weapon at all besides its count
plus y is a misleading name by itself -- instead of yOffsetPerFrame or something
yeah because im trying to base it off the count
so if theres 1 item or 15 or 100 i want it to increase by 1.6 anyway
var yOffsetPerIter = 1.6f / weapons.Count;
for (int i = 0; i < weapons.Count; i++) {
baseWeapon.transform.position += new Vector3(0, yOffsetPerIter, 0);
yield return new WaitForSeconds(0.2f);
}
what are all those error's?
just was trying to use Int, didn't finish the code, says can't cram float into int
no that's not what the yield return null does -- that would normally make the code wait a frame before continuing, but since it's last in your code, it doesn't do anything
has the same result
yeah it's the same functionality,
yeah so whats the change for 🤣
foreach is easier to use IMO
idk sounds fine to me lol, not sure how the coroutine is being called "twice" though
if you want to use the foreach without having it be misleading, use foreach(var _ in weapons)
anyway, misleading doesnt matter
why does it go to 3.6 instead of 2
I told you -- it goes to 3.6 instead of 2 because you're calling the coroutine twice, in code you don't show us
im calling it once in Start, and i checked it just now with a debug.log that runs only once
private void Start()
{
StartCoroutine(Spin());
Debug.Log("Starting");
}
are you adding and/or deleting stuff from weapons then
no, its just a set 20 in the inspector
just curious, why should that go to 2? you said the count was 20 i believe
1.6 / 20 added 20 times is just 1.6
unless this code here is deleting/adding which i dont think it is
try this instead:
var yOffsetPerIter = 1.6f / 20;
for (int i = 0; i < 20; i++) {
baseWeapon.transform.position += new Vector3(0, yOffsetPerIter, 0);
yield return new WaitForSeconds(0.2f);
}
also you should add a debug in the coroutine to see when its started, not in start. not saying thats the issue though
1.6 / 20 is 0.08
so i add 0.08 to the position 20 times to get 1.6 so i can have a total of 2
can you post the logs of y because we don't see how the end result is 2 . . .
inb4 its a child of another object that has scale 0.5
where did that magical 2 come from. and where is this magical value of 3.6 coming from
the chiild has a scale of 0.5 yes, but making it 1 has the same result
ah
i think he meant the parent
the parent has a scale of 0.5 yes
mmhmm
making it 1 makes it work
xD
see i know my code works fine
phew, my brain was starting to hurt just spectating
bruh . . .
this is why its always said to not just read the values in inspector, its local values
how do i make a variable that is checked and changed by multiple scripts?
alright so the solution is just adding half of 1.6 i guess
u can do that with public variables
no smokey grass xD
ffs so what i gotta do 🤣
i can code, but i cant unity 👍
always approach from math standpoint
if you want 1.6 units in LOCAL scale, use transform.localPosition instead of transform.position
oh, i think i see how, thanks man
i mean, was there actually an error of the object being in the wrong place? Again this was just a local value that you were reading.
Anyways this is very hardcoded
ok yeah that works with the original 1.6 value
that makes scale and potentially rotation be accounted for
the scale was 0.5 on the Y, thats the only problem
heck ya, now u got (2) solutions
But what is actual problem?
using position instead of localposition i guess?
yeah. using local is the correct solution lol
No, that is the cause of seeing random numbers. But why do these specific numbers matter?
Why does it have to be 1.6 in the local change?
you should create a public method that other scripts can access to update the value. don't allow other scripts to access or change the actual field . . .
precision offsets i bet
i want the final destination to be 2. the starting position is 0.4
therefore it needs to go up by 1.6
That is what I am trying to ask. Why get it to 2? Because this just seems like an odd way to do it
because that seems like a good number for the gameobject to end up in for it to look alright?
not sure what a "good" way of doing this or basically anything is tbh
Ok. So the problem was that it didn't look good.
Got it
well there wasnt really an original problem, i wanted it to move up and before i coded ANYTHING i just moved it up in the Scene
and found a value i want
now i gotta do the same thing for the time for the yield return 🤣
this just looks like you could use an animation
maybe idk, idk what im doing tbh
its like a cod zombies mystery box
it could be a frog jumping for all it matters. you've hardcoded moving an object with a coroutine when it could be an animation
which would give you way greater control too
wait 🤔
so i can just make an animation of this moving up without any of the amount of things in the list mattering anyway?
that does make sense 😂
then i would just need to code the actual changing of things in the list
i have no clue what the list was for, and you never really stated the true problem. You did say a few times that no matter what you just want it to go to 2 on the y axis. So i dont see why the list affects anything
wait, you just want to move an object up? you can use Lerp for that and easing for t . . .
the only thing thats affected i guess is how slowly it goes up. in which case you still could use an animation and set the speed accordingly. even at runtime
so i need it to move from a to b in idk what amount of time i guess like 2-3 seconds?
and the weapon just needs to go through each one in the list till it travels from a to b
if it travels from a to b, then it will go through every one in the list, no?
a = original position; b = a + 2 . . .
a to b is the position.
so from 0.4 to 2
while its doing that i want the model of whats moving up to change between all the weapons in the list
right now all you have is an object that moves up by a hardcoded amount every 0.2 seconds which i really dont see why this 0.2 seconds is needed. It will look pretty jittery
basically an object moving at 5fps
yeah now i realized that i need it to just go through all of them in 2-3 seconds instead of what its doing now
you remind me of a designer. while fixing one problem, you integrate a new design before the previous one is fixed . . . 😆
what id do, if you dont wanna use animations, is have a start and end point defined as their own gameobject. Or at least some way to visualize it in unity using 2 vector3's and gizmos. Define a float for how long the total movement should take
lerp between start point position and end point position at (currentTime / totalTime)
where did the weapon model changing come from?
🤣
baseWeapon.GetComponent<MeshFilter>().mesh = weapon.GetComponent<MeshFilter>().sharedMesh;
baseWeapon.GetComponent<MeshRenderer>().materials[0] = weapon.GetComponent<MeshRenderer().sharedMaterials[0];
exactly, use two empty GameObjects (or Vector3) fields for the start and end position. another field for the duration. then use a coroutine to lerp using all three fields . . .
yes my IDE is finally configured.
at the expense of half my C drive storage
@rocky canyon it works now
with delay it looks even nicer 🙂
ok, so i made a get; set; for a private variable in one script and i want to use it in a different script, i reference it in Awake/Start to a variable of the same type in another script and anytime i check it, it will be updated based on that private variable, and if i change it, it will update that private variable, right?
also extracted the actual tile movement, cuz idk if i can adjust positions in the list during iteration through the list in c#
since moving tiles technically shall change positions
basically turned both into the "same" variable, right?
you define where and how it changes inside of the get set which is on a public variable not a private one
and in your other script you can just reference the public one
private int something;
public int Something{
get {
return something;
}
set {
something = value;
}
}
yeah, i meant "that private variable" as in the variable the get set variable is getting
when you change the value of the public variable, it changes the private one yes
and returns you the private one when you try to access the public one
@radiant meteor mind that while OK for demonstration purposes, this is a bad practice and causes code bloating
also, you can only reference objects -- int is of type struct, and will only be copied by value when you do var smth = someObj.someStruct
if the property has get; and set; then the private field is pointless . . .
that means that no matter what changes you do to the smth variable, someObj.someStruct will not be changed
i was mainly trying to make multiple scripts have the """same""" variable so i dont have to say "GetComponent<Script>().variable" whenever i wanted to change or get that variable
Wrote the best imo conveniences a month ago: #archived-code-general message
I'd go with the [field: SerializeField] public MyClass field { get; private set; } case then
accessibility modifiers is not really a beginner topic so for now there's nothing wrong with just a public field if you're just starting (e.g.: public MyClass field;)
Reference the wanted component and access the wanted variable. Scripts shouldn't have to declare the same variable simply to avoid proper referencing.
i'm confused, if this for example, "if (!MyBool)" checks "_myBool" which is in another script, and "MyBool = true" sets "_myBool", again, from another script, into true, then why not use this instead of having to reference the script in question every time i want to check/change "_myBool"? if this works the way i think it does, i only need to reference it once in start or awake
@radiant meteor also just to make sure you're aware of static variables:
public class Settings : MonoBehaviour {
public int volume;
public static Settings instance { get; private set; }
void Awake() => instance = this;
}
```..here you can access the volume from any script via `Settings.instance.volume`
Similarly with:
public class Settings : MonoBehaviour {
[SerializeField] int volume;
public static int Volume => instance.volume;
static Settings instance { get; set; }
void Awake() => instance = this;
}
```..here you can access the volume from any script via `Settings.Volume`
typically allowing other scripts (/users) to change a variable that could potentially affect multiple systems is a no-no
access modifiers aren't beginner? 🤔
isn't that the first thing you learn along with classes, fields, methods, etc.?
yeah, as in I would allow my beginner mentee/student to just use public for everything instead of narrowing scope with { get; private set; }
then 2-4 weeks in I'd slap in a long-ass refactoring assignment to make everything accessible only to minimum-required scope 😆
yeah but I don't think that's the thing that shines when learning about classes/fields/methods -- pretty sure those things outweight the access modifiers in the eyes of a beginner
maybe, i guess i'm just wired different. the first thing you type is the access modifier, so i see that as an important concept to know . . .
there's also the possibility that my teaching priorities might be just weird 😛 Imagine I 100% absolutely always start with teaching about how variables translate to RAM blocks
Is there an easy way to understand how world maps are usually done
easiest way to understand how they can be done is to try making one and see what works 😛
how they're usually done is quite vague
I'm not all that far into my world map yet
Sorry, I more so ment the logic behind translating locations and player position into map UI icons
This is done with world to screen point right?
that's fine. the first thing i would teach is the stack and the heap, though, i wouldn't go into gen 0, 1, or 2 . . .
oh yeah my var --> RAM lesson also intends to teach the stack and the heap 😄
nice to hear there's at least someone else who finds that absolutely fundamental
well, the stack vs heap convo would lead into reference types and value types . . .
Ah. Then it's a very complex task. Might wanna look into the following concepts little by little:
- Fade in/out (e.g.: Loading screens)
- Scriptable Objects (e.g.:
EntryPointif you wanna add scene changing like entering buildings) - Callbacks (e.g.: OnSceneChanged -->
TeleportPlayer(EntryPoint)) - Minimap (e.g.: Projecting a 2D icon for a 3D Object over a 2D-projected 3D world)
Mind though that making a minimap is quite a complex task. Since you're asking in #💻┃code-beginner, I'm inclined to recommend skipping it and going with fake world map + transitions
High-quality world maps (like WoW's) are essentially fully-expanded minimaps.
whoa, it disappeared . . . 😲
Hey guys.. Is there a way to show the value of a variable in the inspector but in a way I cant change it? Like just readonly? So I dont have to use Debuglog to see if the value is changing?
use the NaughtyAttributes package or make a custom inspector . . .
the quickest way is to switch the inspector to Debug mode. it will display private variables for you . . .
how do I do that?