#๐ปโcode-beginner
1 messages ยท Page 184 of 1
Read the first line of the description as to why this happens https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html
if you only take F=ma and terminal velocity into account lol
without any other complex stuff
Hi all! trying to get a retro 2d platformer to work but have problems with the jump mech; it fails to check that the player is only on the ground when jump is allowed. Also I want the player to jump using the UpArrow && LeftArrow || RightArrow.
I tried several things, the last thing I have worked well if I only checked for ArrowUp for jump but I need the combo to simulate the old game I'm going for. I use Input.GetAxis for horizontal movement. (So this code still enables the player to keep jumping mid air).
`if (hit != null)
{
grounded = true;
}
if (grounded && Input.GetKeyDown(KeyCode.UpArrow) && Input.GetKey(KeyCode.LeftArrow))
{
body.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
grounded = false;
}`
You want left and right keys pressed at the same time to act as if up was pressed? Is that correct?
(grounded && (uparrow && (leftarrow || rightarrow))
No, I want player jump only when Up + Left or Up+Right are pressed. I need another function for only Up key.
Why you want exactly those combinations?
because they want to only jump up+left or up+right..
to mimic the old control from the Commodore 64. It's actually the joystick movement but I only have the keyboard for the pc right now. ๐
โ๏ธ
https://gdl.space/gujocaqole.cs
can someone tell me why the jump force is always the same, am i missing something?
because you don't change jumpForce anywhere?
sorry, meant JumpIncrease
ye id need to use loops n such here too
I'll try this.
entire Update() is unreadable
id just want it working for now
because you are not nicreasing JumpIncrease anywhere
then id clean up
else if ๐
wouldnt this run the jump method with different JumpIncrease values?
middle parameter is JumpIncrease
it would
yeah it should
timeSinceCharge works as it should, and relaod bar value is always at 1 when i test
Debug.Log it then
in the Jump() method
clampedForce *= jumpIncrease; after this line
Why Im getting this unity error?
I couldnt have asked it 3 times
And its a unity error sure does not sounds convincing
seems that the jumpIncrease is either 1 or 1.25
and i can see why
the else if, right?
or wait no that doesnt make any sense
Sorry, this still makes the player able to jump in mid air. It's like it things grounded = true for too long. If I keep pressing the up repeatedly the player is "flying".
https://docs.unity3d.com/Manual/webgl-texture-compression.html
I've tried to setup a script to automate Build of a webgl project, the 2 outputs just differs texture compression method (1 for PC, 1 for Mobile)
I took the exact script from the Unity manual but I get errors
right, so this isn't your problem.. your problem is that your ground check is too big
How you are checking ground?
`Vector3 max = box.bounds.max;
Vector3 min = box.bounds.min;
Vector2 corner1 = new Vector2(max.x, min.y - .01f);
Vector2 corner2 = new Vector2(min.x, min.y - .01f);
Collider2D hit = Physics2D.OverlapArea(corner1, corner2);
bool grounded = false;
if (hit != null)
{
grounded = true;
}`
Maybe use rayhit?
private void IsOnGround()
{
if (_isGrounded) return; //If grounded just returns. This was made for animator.
var hit = Physics2D.Raycast(transform.position, _rayDirection, 2, _groundLayer);
_isGrounded = (hit.collider != null && hit.distance < 0.51f);
if (!_isGrounded) return;
_lastPositionOnGround = gameObject.transform.position;
_animator.SetBool("IsJumping", false);
}```
This is my rayhit logic with animator changes
private readonly Vector2 _rayDirection = Vector2.down;```
ray direction
I'll check in to that, thanks!
So far it have not failed me. You can change hit distance values depending on where is you character center
You know how masks work? Your ground is on different layer?
Ok, sounds great. Yes the ground is on another layer.
Even if i set it to some numbers its the same
what numbers you were setting it?
to make the ball progressively get bigger
what did you expect?
I think unity just rounded it to 0
not like it would be visible anyway
transform.localScale
Its supposed to multiply the original scale of the ball by that number no?
no you are setting it to that value
this is the value you entered, represented differently
but in 3d that number is multiplied by original scale
Yeah that, if you wanted to multiply it you needed to get original scalke
you could have done it like this
transform.localscale *= multiplier
beware thats gonna make your scale go to infinity
If you want to dinamically scale it save starting scale at start
it's not
its not?
this
then why couldnt i simply use
public vector2 ball
transform.localscale += ball
2d is 3d without one axis
well 2d is 3d in a trenchcoat
you can
You can, but that's not what you had. You had = not +=
yeah i forgot that
@earnest atlas
you wrote public int
so I cant set the number to 1.2 for example
there was another variable that you could do this
then change it to float?
yeah you didnt. my bad. visual studio auto correccted the code i think
what?
arent they?
I mean if we dont consider classes
You can set most of things as float
such as?
I mean size, dimensions, etc
ok, thats 1 component
for geometric data
most of the unity
Let me eat in peace god sake
but you are calling
why would i waste time on that?
then why would I waste my time on that too?
just to prove some random user something
Stop bickering
I did exactly this but it gave more errors
you have the error in the console
operator += is ambiguous on operands of ...
localScale is Vector3
transform.localscale is already a variable
but what did you do here
you dont need to name it
yeah
Im gonna take courses on it but i gotta finish unity essentials pathway first
and they asked me to change 2d ball scale like i did in 3d
you cant finish unity essencials without knowing C#
create public Vector3 type variable
and then add that vector to localScale vector from transform component's property
you are trying to build a roof over un-existing house
I know what the pathway teaches me
thats all
Hello everyone i'm a new beginner for unity currently following a tutorial on udemy. Can i ask a question here regarding to a code i wrote that doesn't seem to work like i wanted to?
dont ask to ask if you can ask us an ask
sure, post the code here
!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.
๐
we are good
no errors
my question is the i am trying to code in a dot aim mechanic where the sword is thrown in the generated dots arc it should be aimed whereever my mouse is but for some reason it doesn't i have taken a video of it on my phone and i don't know if it is against the rules or not?
i belive u can
i think this is it
but why, this is adding useless code
Your DotsPosition() method gives the Y value gravity, which gives you the curve
i see so there is an error in my line 81 and so on i should focus on there
85
Thank you man i will try find a solution over there hope i can ๐
hi i have a problem
I have the code that causes the slide to be detected and the lightning to be created in its direction and position
It creates lightning in the wrong place
why is it happening?
ok i send
!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.
!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.
void Update()
{
if (Input.touchCount == 1) // user is touching the screen with a single touch
{
Touch touch = Input.GetTouch(0); // get the touch
if (touch.phase == TouchPhase.Began) //check for the first touch
{
start_t = touch.position;
end_t = touch.position;
}
else if (touch.phase == TouchPhase.Moved) // update the last position based on where they moved
{
end_t = touch.position;
}
else if (touch.phase == TouchPhase.Ended) //check if the finger is removed from the screen
{
end_t = touch.position;
Vector3 direaction = end_t - start_t;
transform.position = direaction;
angle = Vector2.Angle(Vector2.right, direaction);
if (start_t.y > end_t.y && angle > 10 && angle < 100)
{
angle = -angle;
}
else if (start_t.y > end_t.y && angle > 110 && angle < 200)
{
angle = -angle;
}
transform.rotation = Quaternion.Euler(0, 0, angle);
lightning.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle + 90));
Vector3 mousePos = Input.mousePosition;
mousePos.z = distance_z;
MousePosition = mainCamera.ScreenToWorldPoint(mousePos);
MousePosition.z = distance_z;
transform.position = MousePosition;
lightning.transform.position = transform.position;
//efect_lightning.Play();
//StartCoroutine("active_collider");
}
}
}
did you read how to share code
so you didint understand and just decided to send it anyway in a wrong way
oh i got it
'''
void Update()
{
if (Input.touchCount == 1) // user is touching the screen with a single touch
{
Touch touch = Input.GetTouch(0); // get the touch
if (touch.phase == TouchPhase.Began) //check for the first touch
{
start_t = touch.position;
end_t = touch.position;
}
else if (touch.phase == TouchPhase.Moved) // update the last position based on where they moved
{
end_t = touch.position;
}
else if (touch.phase == TouchPhase.Ended) //check if the finger is removed from the screen
{
end_t = touch.position;
Vector3 direaction = end_t - start_t;
transform.position = direaction;
angle = Vector2.Angle(Vector2.right, direaction);
if (start_t.y > end_t.y && angle > 10 && angle < 100)
{
angle = -angle;
}
else if (start_t.y > end_t.y && angle > 110 && angle < 200)
{
angle = -angle;
}
transform.rotation = Quaternion.Euler(0, 0, angle);
lightning.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle + 90));
Vector3 mousePos = Input.mousePosition;
mousePos.z = distance_z;
MousePosition = mainCamera.ScreenToWorldPoint(mousePos);
MousePosition.z = distance_z;
transform.position = MousePosition;
lightning.transform.position = transform.position;
//efect_lightning.Play();
//StartCoroutine("active_collider");
}
}
}
'''
like this?
๐ 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
void Update()
{
if (Input.touchCount == 1) // user is touching the screen with a single touch
{
Touch touch = Input.GetTouch(0); // get the touch
if (touch.phase == TouchPhase.Began) //check for the first touch
{
start_t = touch.position;
end_t = touch.position;
}
else if (touch.phase == TouchPhase.Moved) // update the last position based on where they moved
{
end_t = touch.position;
}
else if (touch.phase == TouchPhase.Ended) //check if the finger is removed from the screen
{
end_t = touch.position;
Vector3 direaction = end_t - start_t;
transform.position = direaction;
angle = Vector2.Angle(Vector2.right, direaction);
if (start_t.y > end_t.y && angle > 10 && angle < 100)
{
angle = -angle;
}
else if (start_t.y > end_t.y && angle > 110 && angle < 200)
{
angle = -angle;
}
transform.rotation = Quaternion.Euler(0, 0, angle);
lightning.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle + 90));
Vector3 mousePos = Input.mousePosition;
mousePos.z = distance_z;
MousePosition = mainCamera.ScreenToWorldPoint(mousePos);
MousePosition.z = distance_z;
transform.position = MousePosition;
lightning.transform.position = transform.position;
//efect_lightning.Play();
//StartCoroutine("active_collider");
}
}
}
Here we go
Right?
You can edit your posts instead of keeping massive blocks of incorrectly formatted text around 
that's too easy
Can I like... create a method constructor that shares values with another one but is different? Like I want a method to generate a random position in a plane around a point and one constructor is min and max distance and I want another to be like max distance and a random Y offset; and they are all floats, so... is there a way to do this or do I have to just create another method for it?
you can just make a Vector3/2 type function
with different overload
public Vector3 GenerateRandomPosition(Vector3 center, float maxDistance, bool useRandomYOffset)
public Vector3 GenerateRandomPosition(Vector3 center, float minDistance, float maxDistance)
you can create as many overloads as you want
These are the ones I have, I want to add one that is just min and max distance; but there is already one with 2 floats as given values
or you can use default parameter values
right, so you can just shorten it
to 1 function
public Vector3 GenerateRandomPosition(Vector3 center, float maxDistance, bool useRandomYOffset = false)
^^ talking about my example above
you can shorten aswell by using default parameters
Sure, I am having issues visualizing it rn, could you make an example with my parameters pls?
public Vector3 GenerateRandomPosition(float maxDistance = -1, float minDistance = -1, float randomYValue = -1)
for instance
then just check if a certain float isnt -1
and you can call that function whatever way you want
GenerateRandomPosition(); //all floats -1
GenerateRandomPosition(10); // maxDistance will be 10
GenerateRandomPosition(10,10); //max and min distanec will be 10
etc
Oh, I see
guys my game is dropping fps sometimes and spiking, i think it has something to do with memory leaks https://gyazo.com/849e88b4f78faef152b7508030ad70b7 how should i move in this case?
So I would have some conditionals to check the given values, and for example all -1 would return like nothing at all?
sure you can handle it however you want
but yes you'd need some conditional checks
otherwise it would apply the default value
which is -1
Yeah, I am not using negatives for these one, so -1 doing nothing is what I am gonna do, thxs ๐
In this specific code, they are using string.format for a clock
how does {0:00} and {1:00} work together? I am very confused
it works like this
you can lookup string.Format() docs
I did๐
Ah that 1 is placeholder index
at least this what Ive gotten
So if u want hours,minutes,seconds you will write {0:00}:{1:00}:{2:00}
ok
that makes more sense
so the 1 is a placeholder for the next value
alright
No, its just an index
aha
this stuff is really cool
I have been going over it for 10 minutes
it has really interesting properties
I was trying to create a variable in which I will hold for how many minutes the player has played the game
I realized it's easier if I just withold the information at what time he started playing and at what time he stopped
delta time is not that variable
Why?
You could check the Profiler, maybe with "Deep Profile" on to see where you might be causing GC.Alloc to happen most often, if you suspect its a memory leak you should be able to see how much memory is being allocated, but it may not track down which script could be causing the leak, do you maybe have any events you subscribed to and did not unsubscribe or do any expensive operations in Update somewhere?
๐ค
noone said anything about deltaTime?
Your previous approach of adding up delta time was perfectly valid
Forgor to limit spawn to 1 ๐
yeah it was. I though he set it to delta time
don't off-topic
Im just gonna block you ๐
debug.log says its false, even when i dont move and still am touching the ground, i have an idle animation, but it doesnt move the players feet, but could its movements somehow trigger on colliosion exit?
as alraedy mentioned many times
why do you keep checking things by name
that is a terrible idea
and which debug log? there isn't any
yes yes, ill work on that later, even my teacher told me to make names into variable on some sort of general static manager
its in another script which the player has
and is run in update
i understand tag can be more effecient, but im only gonna have one void
where do you call these functions
inside an on collision
so share all the related code, not the code that isn't even related to the issue
https://gdl.space/ukabigivux.cpp the collision code
https://gdl.space/afelenelut.cs the playerMovement code
and what is the issue?
while still touching the ground, isTouchingGround gets set to false
For checking ground by collision callbacks, you need to check OnCollisionStay
source: I do the same thing
not good enough
no difference
big difference
such as?
different things can happen that cause you to change your grounding variables in between, that need to be set correct when touching ground
such as if you jump when in contact with ceiling
Im using raycast to check if Im on ground.
i never set my grounded variable anywhere
or jump off floor while in contact with the same collider as a wall
except in thsoe 2 methods
easy workaround
if(!isJumping)
i have that sort of thing too. Iโm telling you that you will want to check OnCollisionStay
never had any issues and did a lot of projects without it
for ground checks, still I don't see any big difference like you said
commenting it out makes it always trye, so ye this was the problem
this only works if
- Any collision with that collider counts as grounding contact
- player/ground properties do not change
it's more of a design/architectuer issue
than the enter/exit implementation
all my Ground objects have IWalkable interface
if you have a collider that can function as both wall and floor, you will have a problem
because boxes have 4 sides lmao
i don't get what you are saying
you talk about ceiling for example?
that it can be a wall and a floor at the same time?
maybe it makes more sense for 3D, but for 2D sidescroller, you can easily touch a polygonal collider as you pass over a vertex
still don't get it, since your ground check collider is on your feets
if you mean that i can somehow "touch" the ground while jumping and that will count as isGrounded = true
then you can just add if(!isJumping)
this is what happens
first frame make contact as wall at side. next frame make contact as ground. That calls oncollisionStay
2D sidescroller
the box is not made of 4 edge colliders. it is one box collider
i can go into more detail later. but if you do ground checks by collision callbacks, you really need to check oncollisionstay
so like this?
Of course it resets, because you're starting Timer at 1 when this monobehaviour is initialized
Which will happen each time the scene is loaded
doesn't PlayerPrefs save the data?
Yes of course
I am really confused rn; I have a Empty Prefab that just drops coins, this it meant to be called when a enemy dies; the enemy, tells the CoinDropManager what value it needs to drop changing a value, just as it is instantiated. The CoinDropManager, spawn coins prefabs and tells them a random position at which to transtion to over 1 sec, this is directly managed by the CoinDropManager and not the coins. So the enemy is destroyed with a bit of a delay after instatiating the CoinDropManager (0.2sec), the CoinDropManager has Coroutine in start that waits for a instant before dropping the coins (to let time to the enemy to set the value it actually has to drop), then in that same coroutine tells the CoinDropManager to be destroyed after 5 second (more than enough to make the position transition). So the issue is, the enemies sometimes drop the coins correctly and other they disappear mid animation, telling this error. What is happening and why it only happening sometimes?
Think through your logic a little bit
I am a beginner for a reason
You have a brain for a reason
Every update you're saving the value of Timer (rounded)
If your Timer starts at 1 each time this object is initialized, what's the first value its going to save?
The CoinDropManager is something the enemy spawns when they die?
I understand what you are saying
Yeah
But I get confused when I am actually trying to do it
And is it a child of the enemy, or in the root of the scene?
Make a separate method for โCheckTouchGround(Collision2D collision)โ to reset everything centrally. you will later add more things to it for purposes of coyote time, one way platforms, etc. Both collision enter and stay should call this method so that what you do when touching ground stays consistent
the script it going to run everytime the scene loads, how can I make it run only when the game starts and not save it everytime?
These kind of things confuses me
Use the Awake function to set the value of Timer to be the value of PlayerPrefs.GetInt("Timerr", 1)); so it starts with the saved value
I had not specified it, do they spawn as child of the instatiator by default?
No, they'll go in the root
Then it should be fine
Can you share your !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.
This is the CoinDropManager
This is the relevant method from the enemy
Also, you do not need to make separate functions for CheckGroundEnter and CheckGroundStay. OnCollisionEnter and OnCollisionStay should both call OnCheckGround
im not fully getting it, the exit and enter already set values to what they need to be ๐ฐ
You can get a collision callback in enter which is actually not supposed to be a ground collision. Example: Jumping through a one way playform gives collision callbacks that you need to ignore
OnCollisionEnter and OnCollisionStay both need to call a common method that just checks ground contact in a Collision2D
whether you made this ground contact in Enter vs Stay should not matter
but both enter and stay callbacks need to send you to the ground check
does that make sense?
later on, your ground check will get more complicated. You will have more variables, and more shit to manage/juggle. If you have two separate functions for enter and stay that are supposed to do the same thing, it is very likely that at some point, you will change one without properly changing the other.
I think your current GroundColStay would be the exact function I am calling CheckTouchGround
I understand everything, but what is #region PlayerPrefs keys and #endergion?
How do you decide when these coins are destroyed?
The coins have a timer on their own, which is completely separated from these methods
And how long is the time on a coin?
Over 10 secs, should not overlap like at all
In fact the coins have a spawn animation and a despawn animation, they cannot despawn during the spawn animation at all
Your error suggests that a coin is being destroyed somehow, during the process of being transitioned
But just sometimes
Which means you need to start digging ๐
#region tells your code editor that the code between it and #endregion is a..region!
It lets you fold the region up
Do you have legacy code for destroying coins as a test? Keypress? When the player touches them? Or is there a chance that it is in fact, not always over 10 seconds for them to self destroy?
It is complicated XD
actually, I don't think #endregion even needs a name
Oh god I found the Visual Basic docs while looking this up
They have a timer that starts ticking when they spawn, after it ends they satart a fadingin&out animation, which speed up every iteration, when it is fast enough, they are just destroyed
They are also destroyed when the players touches them
Thanks, what I tried to actually ask is what excatly is Region and what it is used for. But that's ok
Kinda, they have a transition for that too
@scarlet skiff if you need to know more details, ping me later
This is why I asked. If the player touches it immediately, it's likely they transition out and destroy while the coroutine that is supposed to be moving them is happening.
Overall, you're relying on three different timers I can count alone, to all sync up perfectly. That's a recipe for disaster.
That's true, but wasn't they issue
They are dissapearing way out of pickup range
But yeah, I have made a conditional to stop the spawn transition if the item somehow becomes null
You can avoid the root of the issue as much as you want, but the fact of the matter is your coins are destroying themselves before the coroutine moving them completes. How that happens, at this point I don't know. You can find it and bandaid fix it, or you can resolve the actual architecturalissue, it's really up to you.
@frosty hound Thanks for the help, I knew what the problem was but I was thinking that I could be wrong the whole time. So I thought it would be better for me to ask for help.
I fixed it ๐
Bit of an annoyance with localization: I have an entry in a string table that's just a variable. The variable is another LocalizedString. It's not assigned by default; it gets something assigned when I use it.
This causes the editor to complain that it can't find a translation.
I presume it's because it gets an empty string.
I guess I should just assign some default value for that variable, so that this thing never evaluates to an empty string?
How do I fix the architeture of that?
Like how else can I do this?
Without completely overhauling the general flow:
-
Don't use coroutines
-
Your CoinManager just needs to spawn in the [x] coins. It should then tell each coin where they should land. It shouldn't be responsible for moving them. So, once all [x] coins are spawned, the manager object can destroy itself (technically, you can just use an actual CoinManager singleton in your scene to do this instead of spawning a new one each time)
-
Each coin will be provided their target position from the manager that spawned them.
-
Each coin will move to that target position in their Update function. And when they've reached that position, begin counting down their timer in the Update function.
-
If the timer reaches 0, destroy self
-
If the player gets the coin first, destroy self
That way, regardless of how this coin is destroyed, it won't throw some error because nothing externally is referencing it.
everything osteel is saying is right
one minor modification: When you plan to destroy self, call instead a โDestroyCoin()โ method, and have DestroyCoin call Destroy
This will make it easier to set up object pooling in the future, or at the very least control timing
It's also nice for when you realize you need to do other stuff when the coin is destroyed
immediately, rather than waiting for OnDestroy to run at the end of the frame
that also gives you a single place where you can say "actually, no, I won't be destroyed"
all this is true
no u in unity
Like I mean, yeah probably a general spawn coind manager for the entire scene; but I though it was way easier to just spawn an empty that spawned objects on its own
The timing between the transitions is not an issue whatsoever
Like it could be more organized, but is working just fine
The CoinManager prefab is working perfectly on its own
Just when the enemy spawn it is giving issues
how can i increase gravity in a rigidbody
So I am guessing this has something to do with the step of instantiating the CoinDropManagger it self
Project settings-> physics-> gravity
alr thanks
if you're in 2D each rigidbody also has their own Rigidbody Gravity Multiplier
im in 3d
I just started unity, until now ive been making games in godot
nicee
btw this is a coding channel, general unity questions go in #๐ปโunity-talk
Would be faster to find a tutorial on that
oh ok
learn how to instantiate, or raycasts etc.
nothing really changed in 6 years
oh so its good? with raycasts
alr
the only code that wont work is if you find a Unity tutorial that still uses UnityScript (Javascript-like code)
using UnityEngine.UI;
public class KamuSpotu : MonoBehaviour
{
public Text text;
public float printTime;
void Start()
{
printTime = PlayerPrefs.GetInt("Timerr");
printTime = printTime.ToString();
text.text = "Just wasted",printTime.ToString(), "minutes of your life. lmao";
}
}
I am trying to make it so it prints the time, at first it didn't allow me to directly print it so I tried to convert it to a string and now it's not allowing me to converts the Integer to a string.
my bad
I am trying to convert it into a string
so make a variable for string..
yes, obviously, but you don't need that line at all
you convert it to string on the text.text line
text.text = $"bla bla bla {printTime} something"
I didn't know
i just found this tutorial for shading an outliner and he creates a "Unlit Shader Graph" or something like that but i cant find it anywhere
you missed the $
ya
gah, edit ;p
@rich adder
text.text = "Just wasted",printTime.ToString(), "minutes of your life. lmao";
But why does this not work?
ur missing +
because it's completely the wrong syntax
not commas
you don't use , at all in string creation like that
oh
thanks ๐, which one would be more efficient/better?
this
I did replace the comma with a + before, but I replaced only one comma ๐ and I was wondering why it wouldn't work
yo navarone
yo
could u help me with this please
bro I don't know how to help you
oh ok
its shading
or design
but in the video he creates smth but its no longer in this version
send me the video
alr
how to make outline shader in unity, outline shader unity, outline unity, unity outline, unity outline shader tutorial, unity gameobject outline, stroke unity, unity shader, unity how to make outline, unity easiest way, game development, game dev
============================================
๐ดCREDITS๐ด
============================================...
this isnt code question
what are the minutes
You already want to work on shaders? you just started ๐
i want to have a black outline around cubes and stuff
r shaders complicated?
yes but shadergraph makes it easier
in the video he makes a "Unlit Shader Graph" or smth like that but i cant find it anywhere
probably because you dont have the package
why would the input system have anything to do with it
like a new input system
why would that be related to shader package lol
okk lol this isnt guess work
thanks
just 3d , yes thats BIRP (built in render pipeline)
a simple one
so one method for both exiting and entering that does different things absed on if its entering or exiting? so would be like a isExiting bool that is set to true if the shared method is called from the onCollisionExist but set to false if its the onCOllisionStay..?
oh ok
also for some reason i can triple jump now instead of double jump
i could just set the jump counter to one, which then would prob mean double jump but yk better to find out why
i want to get you to the point where no exit method is needed
Hi guys, how to make a game like Mini Metro?
maybe itโs time to set up coyote time
but i mean, its not that bad with it? splitting things up could make it a lil more effecient
but idk
coyote time?
trust me, it will make coyote time simpler
coyote time is an amount of time where you are no longer grounded but allowed to jump
like wile e coyote, who would stand in midair for a bit
any good platformer needs coyote time. usually just a few frames
iโll explain how to set this up real quick
Hi, this is my script for car, but for some reason, whatever motor strength I put my car always goes same speed and I want it to go faster. This is my car script: https://hastebin.com/share/cemihocuni.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i assume that is the fix to the on collision stay allowing triple jump
this will fix everything
right now you have
private bool isGrounded = false;
I want you to change it to this:
private float timeLastGrounded = -1f;
private bool IsGrounded => Time.time < timeLastGrounded + COYOTE_TIME;```
when you would set isGrounded to true, you instead set timeLastGrounded to Time.time
this is the timestamp of the last time we were on the floor
checking collision exit from ground is also not needed anymore because we do not need to set a flag to false. And instead of isGrounded as a bool field, we now have IsGrounded as a bool property that automatically checks the timestamp to see if we should count as being grounded or not.
do you understand what I am getting at, and why Iโm doing it this way?
Hi guys Saket here, I wanted to ask some doubts about my project, where can I post those doubts?
In whatever channel relates to your question
doubts about what?
"doubt" is the Indian-English version of "question"
Oh okay thank you :)
About game dev, specifically coding
In my experience most doubts relate to code in one way or another....
yeah exactly
well you're in a code channel. ask away
Ah I will need to phrase it in a proper way, will take some time lol
@scarlet skiff plz confirm
About my previous issue, is there a way of calling a Debug.Log when an object is destroyed? Cause that would help a lot debugging
How can i enable antialiasing in my project
Hello! How can I see the unity console in a Dev Build (with errors, since thats what I wanna find)
OnDestroy is called when an object is destroyed. So put a debug there
I have been looking for the documentation about that, but didn't really understand how to use it, so I might be dumb xd
this isnt code qustion
oh sorry
easiest way to explain coyote time: How long does the coyote have in midair before he starts falling? Let him jump until then.
he said my name
anyways, any possible solutions to this?
Simply make a method and name it OnDestroy()
In a MonoBehaviour of course
It is like start and update, it will be called automatically when the object is destroyed
you're looking wrong then
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDestroy.html
Oh okey, yeah, I might be dumb for not catching that
bruh why does everyone ignore my issue
Nah, just learning. All good
Doesn't look like a code question
Ask on #๐ปโunity-talk
and we are having like 4 different convos on this channel at once
ty for ignoring me, you should have told me earlier
Grow up...
I got here AFTER your question
Sorry did you want all 40,000 people on this server to individually reply to your message with a ยฏ_(ใ)_/ยฏ
people answer when they have an answer... don't feel entitled to one
ยฏ_(ใ)_/ยฏ
39,999 remain
ใฝ(ใ_ยฐ)ใ
i dont even understand what I did wrong since I suddenly get hate
progress
39,998.5 remain
someone replied, and you immediately responded by being an asshole. itโs reciprocal
You are entitled to nothing. If people ignore you, that's just how it goes. But when I DID answer (immediately after seeing your question for the first time), you were rude about it....
Whining about being ignored is always gonna be annoying
I wasnt rude, but lets just keep it like this
Yes, you objectively were. But ok. Don't worry, I won't answer you anymore. Have a good one
Yeah, iโm just blocking him. Too little time for people who refuse to learn.
Okey, so trying to replicate my issue with the CoinDropManager, I think it had to do not with the movement transtion but with this particular line
what would be the best way to make a line of code wait.
Coroutine
coroutine or async
thanks
but probably coroutine
Like I have incremented the timer well beyond reasonable just for testing and it was giving a null reference exception for this one part only, which shouldn't but ok, I comment it out and now I am unable to replicate the coins going missing somehow
I don't know how this can be
A common misconception:
void Update() {
StartCoroutine(ThisTakesAWhile());
Debug.Log("Hi");
}
This immediately logs "Hi". Starting a coroutine will not block the Update method.
i think you have some deeper issues
You can, however, write code that "waits" inside the coroutine
If you're getting a null reference on this line, either itemToMove is null, or that object does not contain a TrailRenderer in it or any child objects
How can i add headbob to my player?
Does this '''itemToMove.GetComponentInChildren<TrailRenderer>()''' retrun null if the object does not exist or only if the component does not exist?
it cant even run if itemsToMove is null
Fuck, I still cannot get the code snipet command rigth XD
So it cause a null pointer?
getting a component will reutrn null if that copmonent does not exist
thats a null ref for sure
It returns null if itemToMove does not have a TrailRenderer on it or any of its children.
If itemToMove itself is null, attempting to call any function on it is a Null Reference Exception
how do i use function in namespace without adding the component (
eg,
comp = gameObject.AddComponent<nsClass>();
comp.doFunc();
does it have to be compiled to a dll to avoid that or is there better way?
Okey, that was probably the issue then
If the function is on a MonoBehaviour object, it must exist to call that function. I don't know what namespaces have to do with any of this
namespaces have nothing to do with DLLs, and they also have nothing to do with your problem
You seem to be using the word "namespace" for something that a namespace is not
if the component doesn't exist, you can't use the component's methods
can you give an example of what you want to be able to do?
DLLs are just linked libraries, usually an assembly
ok thank everyone, maybe i am confusing myself
Explain your actual problem, not your attempted solution.
figured it out, I wanted to do nsClass n= new nsClass(); because in my case it just better way to write it
That's forbidden.
You can't construct a MonoBehaviour instance
Explain your actual problem.
ok so actual problem is i dont know how to add component from namespace using AddComponent properly
it appear red with squiggly line
is nsClass really in a namespace? this code names it directly.
i don't think it's in a different namespace
var something = gameObject.AddComponent<Somenamespace.MyScript>();
yes i think it is
thank you, i think it waht im looking for
then write out the full name: Name.Space.nsClass
There's nothing special about using it with AddComponent
ok
Once you add a namespace to using then it is the same as any other class this script has access to
got it
How would I slow down a player's fall speed? I'm tryna make an Apex Legends type of thing where you skydive and then automatically slow down when you're about to land
my eyesssss
what?
u just burnt my cornea :;(
why?
๐ฆ mode
Don't check for equality, it's basically impossible for it to hit exactly the position 0, 20, 0. And if you're checking height, you should just check height, not X and Z as well
eh, i use discord dark mode and stuff, i just prefer light mode for visual studio, helps me think clearer
anyway I would do a raycast to the floor to check how far from ground you are
yeah i didn't know the command for checking Y only
that's why I did Vector3
i'm a beginner (although i passed the unity learn beginner script course so im not completely new)
ah crap
use .y
alright ill look up raycasting
playerHeight.y
cause if you have uneven ground the distance changes
if(Physics.Raycast(transform.position, Vector3.down, out var raycastResult))
{
if(raycastResult.distance <= distanceFromGround)
{
//slow down speed
}
}```
Something like that
It may look intimidating, but they aren't tough. The most confusing part may he layermasks honestly (at least that's what I see people struggle with most)
gotta learn it sometime anyway ๐คทโโ๏ธ
the signature of the Raycast method makes it easy to plug in nonsense arguments
cool tip: use named arguments
layerMask: myRaycastLayer
Physics.Raycast(origin: transform.position, direction: Vector3.forward, maxDistance: 1f, layerMask: LayerMask.GetMask("Target"))
or maybe
we are delaying setting isGrounded to false by 0.2 seconds. And the way we set it we do so automatically, with a bool property, meaning we dont need to check with a physics method when the player is no longer grounded (on colliosn exit)
Physics.Raycast(origin: transform.position,
direction: Vector3.forward,
maxDistance: 1f,
layerMask: LayerMask.GetMask("Target"))
I'll sometimes wrap the arguments when it gets too long
also very sorry for the late reply i had to leave abruptly
And maybe make a local variable for ray too 
how do you do the out again ?
there is no out parameter for this
oh wait
duh
Out raycasthit hit
RaycastHit lol
i forgor
Physics.Raycast(origin: transform.position,
direction: Vector3.forward,
hitInfo: out var hit,
maxDistance: 1f,
layerMask: LayerMask.GetMask("Target"))
Without named arguments, this looks more like:
Physics.Raycast(transform.position,
Vector3.forward,
out var hit,
1f,
LayerMask.GetMask("Target"))
It's easy to screw up and pass a layer mask into maxDistance
a LayerMask converts to an int, which converts to a float
and now you've made a raycast with a max length of...some random integer
I usually just end up making a serialized variable for it instead, that way can use multiple layers at once and no more converting BS
dang..
15 overloads Jesus Christ
a good couple hundred lines just for Physics.Raycast declaring
interesting signature... ๐ตโ๐ซ
public static bool Raycast(Ray ray, out RaycastHit hitInfo, [UnityEngine.Internal.DefaultValue("Mathf.Infinity")] float maxDistance, [UnityEngine.Internal.DefaultValue("DefaultRaycastLayers")] int layerMask, [UnityEngine.Internal.DefaultValue("QueryTriggerInteraction.UseGlobal")] QueryTriggerInteraction queryTriggerInteraction)
{
return defaultPhysicsScene.Raycast(ray.origin, ray.direction, out hitInfo, maxDistance, layerMask, queryTriggerInteraction);
}```
Not quite. Whenever we touch ground, we log that timestamp. We now count as being grounded from now for COYOTE_TIME number of seconds.
meaning we can jump anytime within that window, even if we arenโt actually grounded
!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.
sorry thnaks for the feedback!
i am trying to display a score on my canvas UI and the script wont recognise the text game object I am trying to use to display the score
" scoreText.text = "Score: " + Mathf.Round(scoreCount);" https://gdl.space/raw/awuzitutum
Anyone know why the camera could be shaking like this?
Does the object with this script on it have a legacy text component on it
i went to 'add component' and added 'text'- not sure if thats 'legacy'
will try and check online
Yes! I thinnk it is legacy @polar acorn
Look for any other objects with the script on it. Search in the hierarchy for t: ScoreManager
You have at least one score manager with no Text component on it
hey you were right!! I had it on my canvas as well - (i also had one random test thing with it on)
hmm i think i get it, so if managed to jump in less than 0.2s after jumping again (czu thats the coyote timefor me rn) id be able to get a third jump, ye?
the score still isnt changing
scoreText is not assigned!
UnityEngine.Debug:LogError (object)
ScoreManager:Awake () (at Assets/3d platformer/scriptzzz/ScoreManager.cs:20)
but eh, i can triple jump nonetheless
wait i think i get it now
Then you still have a ScoreManager object that has no Text component somewhere
Are you spawning them at runtime
when we touch ground we are only grounded for a specific amount of time, but since we have onCollision stay it keeps setting resetting the time.time and therefore we stay grounded
i went and looked again and removed the ScoreManager script from canvas- and now atleast im no longer getting an error related to this script! However the score itself is still not changing
What changes scoreCount
when my player 'picks up' an object with the "coin" tag on it
Show that code
the code of that
that's the same code
also there is no need to update the score every frame
just update it when you pickup the coin
Mathf.Round(scoreCount); that is also unneccessary
scoreCount is a int
I used Invoke and it worked a lot better but thanks for the help
so what are you rounding here? @crisp comet
sorry am looking into this- thanks!!!
line 62 onwards: https://gdl.space/upetodihon.cpp also i have one more script to show you, i feel it'd be more organised if this activity was all controlled by the same script- here' s the 2nd script! https://gdl.space/udedulokip.cpp
Try putting in a debug log whenever you add to the score. See if that ever actually gets called
invoke can be harder to keep track of
Coroutines can be held as a variable and canceled partway through
Yes but coroutines paused my whole game for somereason
that isnโt the coroutineโs fault
Show code
when i removed it it was working fien
i reiterate, that is not the coroutineโs fault
i recommend avoiding invoke in place of a coroutine
a while loop ig
thanks so much!!!!
especially donโt use invoke when you canโt figure out how to make a coroutine work
i guess invoke is better if its being called super often and u dont want garbage collection from the coroutine (assuming invoke doesnt have garbage collection, i dunno actually)
thanks so much!!! was following a tutorial and like, am just trying to get the code to work, but yes ofc would later like to work on improving it as much as i can
Invoke uses reflection which is much worse
yes. We are keeping track of the last timestamp that we were actually grounded. IsGrounded tells us if we should count as grounded based on the timestamp
Invoke is so much worse
oh dear. so basically invoke should never be used?
correct
yep
invoke calls a method by string
you are literally sifting through the names of the different members of the class to find the method. Instead of just having a pointer built in to send you directly to the function
every single time you call invoke
you also open yourself up to Invoke(โCheckGrondStateโ)
unless you use nameof, and anyone who knows to use nameof knows not to use Invoke anyway
thats good to know, thanks! i've never used it anyway but after hearing coroutines cause garbage collection i had a thought that invoke may be better then. glad i found out the truth
The best way to handle timers is to do it manually in Update using deltaTime and math. Coroutines give up some of that performance for code cleanliness, and there's a certain point where code cleanliness is worth the sacrifice
coroutines cause garbage collection because you need to instantiate new WaitForXXX objects every time you delay a part of the coroutine to the next frame
it's a miniscule cost for a pretty sizeable gain
I'm trying to set a tile of my tilemap with a new sprite like this
gs.tilemap.SetTile(coords, paving_tile);
but even though both tiles are made from sprites that are the exact same size, the new one is a lot bigger. I can't figure out why this would be
Compared to the significant gain over Invoke
coroutines have a small garbage collection cost, which is only a problem if you spam them everywhere in a game
does setTile automatically rescale or something?
no
Tilemaps are usually going to be on a child of an object with a Grid component
grid defines size
tilemap basically holds tiledata on a matrix. grid lets you move between cell space and world space
so its something in my tilemap settings?
check your Grid
I just don't understand how if they're the same size sprite it would be different for the new one
so I'm not even sure what I'm looking for
what do you mean
I created a .asset file
what
oh, youโre doing it that way
Hello, could someone help me with this script? The particles arent playing
void Die()
{
onDeadParticles.Play();
Destroy(gameObject);
}```
you can drag a sprite to a tilepallete to automatically make a simple Tile btw
why would they play when you Destroy them at the end of the current frame?
how big is each sprite in resolution
oh well when i shoot the enemy many times enough i want him to die and emit those particles
when you sliced it
Is onDeadParticles on this object or a child of it?
then dont Destroy until the particles have played
but he isnt destroying the particles
and maybe they are unparented
but i want the particles to play after the enemy dissapears
Then you're destroying the particles
bet, the particlesystem is on gameObject
then they need to not be a child object of the thing you're destroying
unparent them then play
or figure other way of doing that
and what about the position
what about it
how do i set the particles to play in the center of the enemy
the same way you are doing it right now
just unparent it
before destroying gameObject
ooh, and the parent should be SampleScene?
The parent should be nothing
oh ok
what
- when you sliced it, are the regions for each tile the same pixel-wise?
- are you comparing two different tiles on the same tilemap? Or are you comparing sizes when putting them on different tilemaps
they look the size on the tilemap, but not in game
oh wait
maybe the farm is bigger in the tilemap
nope, only one. the right side is a tile palette, sorry
a tile palette is just going to show you the tiles
one tile per cell
did you slice the sprites for each tile?
how do you slice
thatโs your problem then lmao
for this sort of thing, iโm expecting multiple tiles to be in one PNG file
in unity, go to that PNG file, set sprite mode to Multiple, point filter, no compression. Then go to sprite editor
then draw a little box (which should be the same size every time) around the area that should be the sprite for the one tile.
click in the little green highlight square to see the name etc, change the name to be something useful. Save
now when you look at the PNG in unityโs project view, it should show a little tab of multiple images, one for each sprite that you just sliced
ok but I'm confused. the whole png should be exactly one tile
nope
each PNG should contain MULTIPLE tiles. otherwise you will make your life more complex with tons of tiny little files
and tracking them down and all that shit. trust me, it is better to slice.
you're saying I need to take all of my sprites and copy paste them into the same png file, then cut them again?
that seems like a lot of work for no reason
Thats what a spritesheet is
you donโt need to, but itโs prettt weird to have made so many separate image files in the first place
A typical file used to make tiles typically looks like this. all in one file
you do not want to mess with this exact same file into like 100 separate PNGs
Thats where the slicing part comes in.
slicing is where you define each little region to be a separate sprite
ok, i've made a spritesheet
since you had your farm and grass in separate files, I bet they had different resolutions
ie different pixel x pixel measurements
(which is really bad)
now slice, and show us the sprite editor
also there is an auto slice function in unity. If you ever use it, ALWAYS set it to โSafeโ mode, or else it will delete your old sprites, and break anything that references those sprites you just deleted
i donโt know why this is not default
_target = GameObject.Find("Player").GetComponent<Transform>();
Will this give me transform position of object in real time?
don't ever use any Find methods
Serializing playfield player GameObject is not fun in mutliple entities
How do i check if a particlesystem is done playing
IsAlive or you can just use length to destroy it
if i use isAlive it doesent work
why does give an error, i do infact give it an object reference..
private ParticleSystem _particleSystem;
void Start()
{
_particleSystem = GetComponent<ParticleSystem>();
StartCoroutine(DestroyAfterParticleEffect());
}
private IEnumerator DestroyAfterParticleEffect()
{
while (_particleSystem.isPlaying)
{
yield return null;
}
Destroy(gameObject);
}```
I have this class in all effects
So far it worked fine
โmethodโ should always be set to โsafeโ
Where do you assign playerMov
in the inspector
also 360 x 360 is massive for a tilemap
I think ur assinging the class itself and NOT a instance / Gameobject in the scene
and ot gets passed from that script to the initiated bomber
Then there exists at least one Bombardment that does not have it set
if you you have a 1080p display, and your tiles are 360x360, then that image will get compressed if you try to show an area taller than 3 tiles.
which is very bad
np
it is a Gameobject in the scene
standard tile sizes are 16x16 or 32x32. Maaaaybe 64x64 for some really chonky stuff, but 360x360 is not going to end well for you, @ashen wind
Search t: Bombardment when the error occurs and find which one has no playerMov set
sorted it out! Thanks for directing me towards the other script. i didnt realise the coin tag + scoring was being handled by another script. chat gpt helped me - "It seems you've included the OnTriggerEnter method inside the Update method of your MovementScript. This is not the correct placement for OnTriggerEnter." thanks so much!!! also thank you @rare basin
the ones with Bombardment dont exit in the scene they only get initiated via the spawner, which has a reference to the player
can i make my custom variable have required input when creating new() one
So show that code
yes
Your using the coroutine that references the playerMov before you assign it
You start the coroutine inside of Bombardment as soon as the game starts but u only assign PlayerMov on a Button press inside of the Update Function inside of the BomberSpawner class
bomber spawner: https://gdl.space/bifomesama.cpp
bomber script: https://gdl.space/anolujikog.cpp
i assign it right after initiation tho
These aren't relevant. Where do you assign playerMov to a Bombardment
Again u dont
Also what is this
Why does Bombardment have a reference to itself
that is never used
in the bomber spawner, here
where
bomber.playerMov = this.playerMov
nothing in this sets the playerMov of a Bombardment
why did you name the Movement type variable
bomber
it is sooo confusing
also what is this line
bombardment.bombardment = this.bombardment
i put the bomber prefab there, but movement script can be shared with bomber and archer
this doesnt kinda make sense
None of this matters
ye i realize now
Where are you setting playerMov on a Bombardment
im not rly sure what u mean now ๐ฐ
Bombardment has: public PlayerMovement playerMov;
which is only given a reference upon initiation
via the spawner
which has its refrence from the inspector
yes but where do you assign
the playerMov from the Bombardment class
through inspector?
ye the spawner has it
stop
listen to what we say
no one asked you about the bomber spawner script
Bombardment class has a playerMov variable
where do you assign it?
in the BomberSpawner script.... ...? is that wha u mean? sorry bro i dont get it
jezus
Where though
Those arent the same class
Where in the spawner do you set it
You never assign the Bombardment.playerMov you Think you did
should i be doing this instead?
bombardment.playerMov = this.playerMov;
or both
probably
If you want to assign the value on a bombardment yes
But where are you even getting this bombardment from anyway
You aren't spawning it
And you said there's none in the scene
So what is this bombardment
i think i got conused cuz both movement and bombradment had a variable that does the same thignb with the same name
it is a component of the bomber prefab
you spawn your bomber prefab
as a Movement
So where do you set the bombardment variable on this object
Im using Time.timescale = 0 to take a chunck of my game pausing away. but i want the animator on the player to play. so on the player controller under update im doing _animator.Update(Time.deltaTime * 1f); but its not working. what am i doing wrong
i dont think multiplying something with 1f does anything FYI
If timeScale is 0, deltaTime would also be 0 I believe
theres tutorials for playing animators while game is paused btw like this https://www.youtube.com/watch?v=mwNlOrD6vFM
Be sure to check out my Unity for Complete Beginners course on Udemy here: https://www.udemy.com/course/learning-unity-and-c-for-complete-beginners/?referralCode=23B51187C8A97B78D1CF
In this video I will show you a fast Unity tip on how you can play animations in regular time when you alter the timescale of your game. Changing the update mode o...
cheers
you can use unscaledDeltaTime
timeScale-independent
thank you
Hey, can anyone explain / give me a video explaining how to find the displacement of a 2d object through recording 2 positions (specifically the recording of the 2 positions) I've tried searching for it but nothing explaining the recording of 2 positions
wdym? just have a component record current position in LateUpdate or something.
Lateupdate ill look that up thanks
you will possibly want to do this in FixedUpdate after physics sim, tho
should physics calculations always be recorded in fixed?
in my case, i call Physics2D.Simulate manually, so I can call code naturally right after all collision callbacks are done. This lets me call an event action called OnAfterCollisionCallbacks
always
ok cool
thanks a lot
do not do any physics in update.
sure
btw you need to set Physics2D similation mode to script to do it that way
Physics2D does not want you to call Simulate unless you set that mode
oh ok