#💻┃code-beginner
1 messages · Page 175 of 1
but it's actually blurry?
huh even just recording my screen doesnt show it
try removing the setfloat ing the fixed update
This video kinda shows it
no clue what that is but i guess
yeah that
yea, try removing one of the set floats
that may be messing up the animation timing
remove the one in the input catcher
not sure about new input system, but can you try placing that in Update instead?
then the velocity will become a class field that is updated by the input system
still is a little glitchy but its better
controlling animation in fixed is glitchy yea
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/IMGUI/LayoutGroup.cs is this the layoutgroup csref?
no. it's part of the UI package
https://github.com/Unity-Technologies/uGUI/blob/2019.1/UnityEngine.UI/UI/Core/Layout/LayoutGroup.cs
Nah, LayoutGroup is UGUI, that is IMGUI . . .
so painful navigating github, cant ctrl+click thingies
so download the repo
this code is also already on your computer as vertx has pointed out to you multiple times
what am i doing wrong here, its always fully filled, as if it ignores fill amount
and is this code actually running?
Note also that in order to change the image mode to Filled you have to assign a sprite to the Image. It can be a 1x1 white pixel image, but it must have a sprite assigned regardless.
wait what why does my image component not even have that option
ah okay thanks
yeah, this is a bit of a nuisance
i was looking into creating a filled, sliced image once
the code is scary
a mask is a decent approximation, but those edges are hard ):
does anybody know how to get rid of this box and get the little line back? it overrides the text instead of adding to it
press the insert key
works now ig, had to use a coroutine though
wait so in the tutorial the guy gets the fill to be in the x axis, mine fill in a wierd pattern, bottom left, top left, top right, bottom right
how do i make it X fill only
nvm found it
Because you need to change how you fill it, there are options. Make sure to follow the tutorial correctly . . .
how do i get a scene, from a loadSceneOperation, or its name, so i can use it in setActiveScene?
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html
LoadSceneAsync returns an AsyncOperation you can check the status of and then get the scene object from when it's finished.
so i store the asyncOp then get its scene?
try it and see
Once it's done loading at least
even tho i am setting the newly loaded level, my objects are still instantiating in the scene that was initially loaded(my scene manager scene) do you know what im doing wrong?
AI_Test is the scene loaded through the coroutine
oh wait i think i now what i messed up...
gimme a sec
i was setting isLoadingLevel to false, my bad. sorry for the ping
Is there a way I can create functions, that I can call from every project?(like Vector3) or something?
Every project, no. You'd have to put the code in that project to use it there
Create your own package and import it into each project . . .
It's just like importing Unity packages. When you update your package, you hit the update button in the package manager to grab all the changes . . .
It's great for core functionality that you use as a base on any project and extension/utility methods . . .
How do I acess them then without having to create a refrence to them everytime?
wdym by "create a reference to them everytime"
Having to do private Script scriptname and in the code scriptName.Function
That's accessing an instance method, which is only accessible from an instance . . .
You want to create a static method that can be accessed from the class itself . . .
make them static, but beware this can have unforseen consequences
If you want helper functions you can make a static class. Then add using static ClassName; and you can call its methods without specifying ClassName each time
make a static class with static methods, then u can call those methods from everywhere
Such as?
Either that or extension methods . . .
ok but then I still have to do name.instance.Function, right?
'there can be only one'
so only one static method or one per name? lol
also vector3 is a struct so u can put a struct somewhere and use it anywhere
No, you access it via the class: MyClass.MethodName . . .
ok thanks I will look up extesion metohds, instance methods and structs
I would read about static methods and extension methods . . .
static classes and methods can only work with static variables, so by making the class or method static you are limiting yourself to only have one version of the variable. The singleton pattern is, of course, an exception/workaround to this
Smith family reunion, nice!
hmm, with a name like Josh I doubt we're related, there are lots of different Smiths
There is an infinite amount. I just like the fact that John, Josh, and Steve were all united, speaking at the same time . . .
this is my script for dashing but when i dash i won't move forward, any ideas?
Best guess is that movement code overrides the velocity
I was thinking of friction and drag coming to play.
AI generated code?
yes
I guess, too many comments.
not only two many but completely obvious and stupid
then read #📖┃code-of-conduct
Always coming back to that vid by code aesthetic. 
Getting the direction by focusing the distance and time doesn't make sense . . .
In 2D, how can I gradually move an object using script? I don't want to use Vector3 because that'll just snap the object to it's new position, I want the object to 'slide' to it's determined position
Do I use Lerp?
nothing ai generates makes sense
we are not here to fix crap generated by AI because OP is too lazy to write their own
ye
Well, I want to make a fist for an enemy that will move back a little, then spring forward. Like a punch
So I would use Lerp for that, right?
maybe a curve
I thought it was for UI.
if you want a possibility to clip through walls sure ( moving transform directly = clip through walls)
Hmmm I've never used curves before
otherwise use rigidbody + forces
animator good for like very specific movements like abilities
@unkempt maple NEVER DM someone without their permission
Using a Rigidbody isn't working because when I attach one to the Enemy's fist, it either makes the collision between the first and the player's body act weird, or the fist starts flying off the body towards the player
My enemy will have 'Rayman' style hands. No arms, just floating hands that will punch
☝️ 🤓
if you want optimal collisions hits figure out a way to make it work with rb
lets talk in private and not here
No. That is not how this works
Don't DM people without asking first
why not
make a thread if you want your own conversation room
They just said no private convo's . . .
why not is because you don't command somebody to talk to you
It's literally the first rule
okey daddy
Plus you JUST called them a nerd, why would they even help you anymore?
i dont want his help i want to explain him something in peace
Weird...
Calling someone a nerd on a game development help discord is like... yeah. We know. That's why we're all here.
"Im using AI because I just ran out of gas and need to get to my house this one time , if you can just help me out this time"
Then create a thread and hope they'll read it . . .
or at least just ask nicely
there is no need to ask for people like him
Ain't gonna happen, too late, move on
yeah big daddy said move on
I want to make the enemies fist move back and forth, to simulate a punch, when the player enters the trigger which is infront of the enemy. Would doing this by code or animation be better?
either approach is valid and it depends on how you set up the enemy. is it gonna be just one sprite?
Yeah
Using code gives you the option to very easily parameterize it to do things like adjusting the wiggle direction and amount.
Using animation gives you the option to actually animate it later with an actual animation.
I'd say go with whichever one you're more likely to want to expand to later.
Hmmm, probably code. I'm just struggling to figure out how to do it
if you have a punch animation, use that. you can use the animation system to perform specific actions on specific animation frames. take a look at this https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
The easiest way would be to use a Tweening library like DOTween. It's not terribly hard to code simple movement like this but a tween library is really nifty to have and if you got it you might as well use it for the simple stuff too
Never heard of a tween library before. Will look into it
It makes moving objects easier, right?
As in animating, but using code?
Yeah, it creates "in betweens", so you give it a start thing, and end thing, and a time to do it in, and it changes that value between those two endpoints over the given time. You can use it for basically any continuous value, not just position.
It would manage the interpolation for you.
At any time the start and end points are fixed quantities at least
hmmm ooooookay
Since importing DoTween, I have an error message saying 'Failed to find entry-points:'. What does this mean?
Maybe show the actual error and stack?
hi, i cant drop a sprite on the animation anyone knows why?
this is not a code question
what is it then?
Trying to use DoTween. This is my code at the moment, I want the object to move and then move back to it's starting position but it's just moving, then not returning. Anyone know why?
thanks
Because you're only tweening to that location, nothing about this moves it back. You're probably going to want a sequence that moves it somewhere, then back
ooh, I thought the SetLoop would bring it back? I'm following a tutorial and it did for that guy
So is the SetLoop pointless here?
loop itself doesnt mean it will go to first frame again backwards
if there is loopmode to reverse then sure
lookup the LoopType
the docs for dotween sucks a donkey I can't link you directly to it
https://dotween.demigiant.com/documentation.php
DOTween is the evolution of HOTween, a Unity Tween Engine
Hi y'all, i got an issue, I need a variable to be from 0 - 1, but it's currently between 0.21 - 0.72, because the object i'm clicking on doesn't take up the whole width of the screen
how do i convert variable to 0 - 1 rather than doing this?
the variable is basically input.mousePosition but converted using ScreenToViewportPoint() so clicks are resolution independant
I can show you my code for more context but I would like to know if it's possible to get an idea of how to fix this issue?
https://docs.unity3d.com/ScriptReference/Mathf.InverseLerp.html
InverseLerp, does the opposite of a lerp. Takes a value between two arbitrary endpoints and gets the normalized 0-1 value of it
how can i find gameobject by name and the gameobject is disabled in hierarchy
FindObjectOfType(includeInactive: true)
Can someone help me with my code. I tried to run it already a buch of times. I am trying to make a zombie's health go down when it hits an object tagged as "Bullet" but it just doesn't work and I don't really know why
Here's the code:
using UnityEngine;
public class ZombieController : MonoBehaviour
{
public Transform player;
public float speed = 2f;
public int maxHealth = 20;
public int bulletDamage = 10;
private int currentHealth;
private void Start()
{
currentHealth = maxHealth;
}
private void Update()
{
if (player != null)
{
Vector3 direction = player.position - transform.position;
direction.Normalize();
Quaternion toRotation = Quaternion.LookRotation(direction, Vector3.up);
transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, Time.deltaTime * speed);
transform.position += transform.forward * speed * Time.deltaTime;
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Bullet"))
{
currentHealth -= bulletDamage;
if (currentHealth <= 0)
{
Destroy(gameObject);
}
}
}
}
!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.
-_-
Sometimes I hate it so bad.
But it sounds like a person talking, which is all it actually does
It doesn't know anything about code, it just puts words together in ways people do
stop asking ChatGPT things
I had issues with thing not working
It's not an oracle it's a very complicated markov chain
is it possible to set an object as invisble without disabling its meshrenderer or giving it an invisibility mask? I have an object that needs to cast shadows and thus have its renderer on but also has a mask used for LayerMasking, is there another possible solution?
oh yeah that exists
The only thing that the spam generator should be used for is to generate spam
It fails even at that 🙂
no, it's GREAT at creating spam
I tried to make it create dummy data for me. It takes forever for it. its faster to write it with code
Does someone maybe have an article abour Camera.main.screen... I'm wanting to make it so the player looks to the cursor in 2d top-down, but im not sure which to choose
Camera.main.ScreenToWorldPoint This for example
heck ya, looks good
I've made small collider on player but its not detecting collisions?
void OnTriggerStay(Collider other)
{
if(!other.CompareTag("Ground")) return;
GameController.Instance.IsOnGround = true;
}
void OnTriggerExit(Collider other)
{
if (!other.CompareTag("Ground")) return;
GameController.Instance.IsOnGround = false;
}
Solution found on stackoverflow.
Ground is tilemap with tag
private void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "Powerup")
{
powerUpEnabled = true;
PowerUpStart();
other.gameObject.SetActive(false);
Invoke(nameof(PowerUpEnd),timeLeft);
}
if(other.gameObject.CompareTag("Portal"))
{
isTeleport = true;
initialPosition = transform.position;
originalVelocity = rb.velocity;
rb.velocity = Vector2.zero;
rb.gravityScale = 0;
objMesh.enabled = false;
Invoke("TeleportFinal",FindObjectOfType<CamFollow>().teleportTime);
}
}
void PowerUpStart()
{
rb.mass*=3;
physics2D.bounciness = 0.5f;
coll.sharedMaterial.bounciness = 0.5f;
Debug.Log("Power up started");
}
void PowerUpEnd()
{
Debug.Log("Power Up ended");
rb.mass/=3;
coll.enabled = true;
coll.sharedMaterial.bounciness = 0.97f;
powerUpEnabled = false;
timeLeft = 3f;
}
So what this code basically does is that it reduces my ball's bounciness. This worked perfectly fine in 3d(with all the necessary code changes like changing from Collider2D to Collider) but in 2D it doesnt seem to change my ball's bounciness
also i tried using both physics2d.bounciness and coll.sharedMaterial.bounciness but both are not working
in my 3d version i used coll.Material.bounciness
any problem with my calculating logic? whenever a non planet collides the score just becomes negative...
Is a planet is always false
nope
i set it to true
in the inspector
and the score becomes positive
but as soon as a non planet collides it just becomes negative
Make score static I had similar issue
Example: a planet collides 5 times making the score 5, a non planet collides, suddenly the score is -6
lemme try
:((
I thought private is shared
hi, when i start my project my camera rotation is good but when i start it the rotation change
Private is private
pls
give more info dawg
I'm trying to get the plane to look at the mouse cursor, in 2D top-down. It looks like it's moving, but just on the Y axis it seems like?
Vector2 mouseWorld = Camera.main.WorldToScreenPoint(mousePos);
transform.forward = mouseWorld - mousePos;```
After some digging I found that WorldToScreenPoint can only be used in Vector3, is that correct? If so, what do I use to get the Camera.main. to what ?
What is a physics2D?
this is a code related channel
You can ignore physics2d
If you're working with 2d, you need to use the 2d variants.
Yes i did
Not knowing what physics2d.bounciness is, I'm simply going to assume that it's something incorrect.
Bro ignore that
If i delete that statement nothings gonna change
Im talking about coll.sharedmaterial one
In my 3d version of this game the code works
But in 2d it doesnt
When i look at the physics material attached to my ball in the 2d version the bounciness gets changed to 0.5 but it doesnt bounce less
It bounces to the same height
Anyone ?
I've got no clue if you know what you're actually doing but 2d uses the 2d physics material and 3d uses the 3d physics material.
Using a single type for both is likely your issue.
I told you
That i use 3d in 3d
And 2d in 2d
I used collider2d in 2d and collider in 3d
I literally wrote thay
That
void Start()
{
colliderHeight = GetComponent<Collider2D>().bounds.size.y;
}
void FixedUpdate()
{
var hit = Physics2D.Raycast(transform.position, new Vector2(0, -1));
if (hit.collider == null) return;
//This just does not want to work...
var groundDistance = hit.distance;
GameController.Instance.IsOnGround = groundDistance < colliderHeight;
Debug.LogWarning("Distance to ground: " + groundDistance);
}```
Why its not working. Its hitting something Idnno what
I have disabled This
i'm not sure your code even tries to do what you want. you have the coordinates of the mouse in screen space. then you try to convert those coordinates from world into screen space and then you use that to make a forward vector. but mouse pos is in screen space already.
if you want to make the plane look at a point, you need to get "world coords" of your click. you can try doing this by intersecting a vector from camera to an invisible plane that defines your 2d space. that gives you a point in your 2d plane. then i think your plane's "forward" would be that point minus the origin of your plane.
WorldToScreenPoint can only be used in Vector3, is that correct?
Yes, but that isn't an issue as Vector2 is simply a Vector3 with one less component.
You need to use the screen to world function to convert your mouse position to world space.
https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
Make sure to adjust the z value of the converted point to your necessary value if needed (it'll be at the camera's depth.. default at negative 10)
Are you certain it's hitting something?
Consider showing the console logs.
It is hitting aparently itself
EVEN tho I have disabled that
Im about to go checking rigidbody speed and just throwing this code out the windows
Im just making corutine thats going to wait 0.1s before checking rb speed again and then letting player jump
I hate raycast
Well, the raycast starts at the origin of the object so it would most definitely hit that object without filtering any layer masks.
I dont understand how layer masks work, I dont have time to understand them, Ill just make it normal way instead of using rest of my day dealing with that mess
then don't expect anyone explaining it to you
when you dont have time to understand them yourself
Whatever floats your boat
Ive spent last hour trying to make it work
Or I can make corutine that waits 0,1s and does not needs any raycast
do whatever you want
So, should I do the z axis - the distance the camera is in screentoworld?
so for example - 7.51
The most common errors with layer masks are:
- You passed a single layer instead of a mask.
- You passed it at the wrong place in the method, which means your ray distance is the mask, and vice-versa
I'll probably deal with layers and masks when my Ahdh calms down.
Masks convert to numbers seamlessly so it's very easy to make mistake #2 and not be aware of it
so im displaying the cursor cords i do that minus the camera?
sorry, one way to get a click location in world space is to do a ray cast from camera to the surface you're querying
Camera.ViewportToWorldPoint
but you can just use something like https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
Do I place a new Vector3 in there or just the mousePos + 7.51 (z-axis) or even both? Sorry I am trying to understand here precisely what is happening haha I thought of it way too easy
you can do new Vector3 with mouse.x, mouse.y, and then whatever z your 2d stuff is at
did you read the docs?
you can use viewport but if you use screentoworld, you can directly use the mouse coords. otherwise you will have to normalize mouse coords to [(0,0), (1,1)]
I'll have to run for a bit. I try it out later, thanks so much for the help guys!
Hello, so I'm spawning two game objects that both get destroyed and I would like create a count(on debug console) that displays the number of times the spawn is destroyed. Meaning whenever the game objects collide the count increments. I have everything setup with the collider components and all that. But when I run the script it does not increment, I'm not sure what is wrong, any help is very much appreciated, thanks.
Here is the code snippet :
void OnTriggerEnter(Collider other)
{
fed++;
Debug.Log("Score:" + fed);
Destroy(gameObject);
Destroy(other.gameObject);
}
Show 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.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class DetectCollision2 : MonoBehaviour
{
private int fed = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider other)
{
fed++;
Debug.Log("Score:" + fed);
Destroy(gameObject);
Destroy(other.gameObject);
}
}
- Actually follow the instructions for posting code
- The only time you increment
fedis right before this object is destroyed so it's never going to ever be more than 1
Each script on an object has its very own copy of that variable. When you destroy the object, the variable and its value is lost forever
I had thought this was the case. How can I go about incrementing the value, if the object is being destroyed. Or what is the alternative?
The easiest way by far is making the variable static. That way it's "shared" across all scripts, and its value persists until the program stops running.
Okay, but even if I do it after. It's still not incrementing.
Well, incrementing a value after an object is destroyed ins't going to make it last any longer
Is this going to get me executed, or is this acceptable
You should learn how to use Enums
(Is there a better way of doing this that's gonna blow my mind)
and a switch statement
Thank you I will research them
Thanks, will try and see how it goes.
Okay, how could I go about it?
Don't put the fed variable on the objects that are going to be deleted. Put that variable on something that sticks around and have that thing increase in value whenever one of these objects is hit
Mate, thanks alot it worked!!
also i dont get why u use ints to store the race
What should I use instead
a string?
like if ur gonna use a method that inefficient to set stats, you might as well use a string lol
It's a seperate object, it only needs the int
ok yeah using an int to resolve to the string is pretty silly
see if this helps https://learn.unity.com/tutorial/introduction-to-scriptable-objects
you can make a ScriptableObject for reach race and include data other than their name
either scriptableobjects or just use static fields probably
or even better, structs
you could technically use an array of structs to create a race list
It works, but could I make it that the score is displayed once and incremented from there and not repeated as this. Thanks again.
so u dont have to make comparations for any reason
i'm not sure it's helpful to suggest every possible way to solve the problem
u just have a race that contains that value in itself
well im just saying a few solutions
Isnt that just objectively less efficient
he can choose any he wants
An enum, as I said earlier
yeah digiholic is right, an enum is the best start
not you digi, i mean the person telling me to store it as strings
im still watching vids on enums
you can use an enum to replace both pieces of what you have now but i'm not sure that actually gets you anywhere
it'd be better for clarity I believe, but yeah I suppose ur right its not really relevant
I don't know what you mean, it doesn't look like anything is repeated there
magic strings bad
debug log prints something into the console and thats it. it can write on it but it can't change something you've already written
i think he wants a single Debug.Log() message in his console and have that changing depending on his score
i tried this and other methods/ways for 5 hours straight,
private string Owner = "electrum-bowie";
private string Repository = "myRepo";
private string Token = "hidden";
public async Task UploadWavFile(byte[] bytes)
{
if (string.IsNullOrEmpty(Token))
{
Debug.LogError("No access token.");
return;
}
try
{
string fileName = "speaker.wav";
string commitMessage = "Upload " + fileName;
string apiUrl = $"https://api.github.com/repos/{Owner}/{Repository}/contents/audios/{fileName}";
var fileContent = Convert.ToBase64String(bytes);
var requestBody = new
{
message = commitMessage,
content = fileContent,
branch = "main"
};
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", Token);
var jsonBody = JsonConvert.SerializeObject(requestBody);
var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = await client.PutAsync(apiUrl, content);
response.EnsureSuccessStatusCode();
}
Debug.Log("File uploaded successfully.");
}
catch (HttpRequestException ex)
{
Debug.LogError($"Error uploading file: {ex.Message}");
}
}```
i just get:
Error uploading file: An error occurred while sending the request.
or
Error uploading file: 403 (Forbidden)
please.. this is so easy..
at that point ur better off using some sort of UI element tho
Logs don't change
thats what I explained right above that yup
The server refused the request. Make sure the API key is valid. Try sending the request using another program, like Postman
What I meant is that it print the score: 1, then score: 2, then score 3 and so fourth. But I would like for it to print score but the values should increment and not the entire statement. Hope that was clear.
also idk how thats #💻┃code-beginner ill be honest lol
is the code correct? i don't get
Error uploading file: 403 (Forbidden)
anymore...
networking stuff doesnt look beginner
Yeah I understood, you can't do that in Debug.Log(), because it just prints something in ur console and thats it, that can't be changed
what you can do is add a UI Text and have that display the score for u
it is though, depends on what beginners begin learning on :/
I made a simple animation to a cube which uses navmesh, if I have root motion on, the sheep won't move, if it's disabled the animation won't work, anyone knows a fix?
Yes, this is what I meant.
Well yes it's valid, since the request is sent and it's the EnsureSuccessStatusCode() that throws the exception you catch right away
have u ever made a console application?
basically something like a "Hello World!" script
and printing it in ur command prompt or terminal
With the Code above, i only get:
Error uploading file: An error occurred while sending the request
I just want to know what did i miss.
The Access Token is valid
it has all permissions active
well if you start learning on something advanced that doesn't make the thing "beginner" lol
but tbf at this point ur better off just getting help here yeah
it makes the thing beginner from the perspective of Unity Knowledge
well, difficulty is subjective
Start debugging and inspect the ex variable, it may have more info in it
but lets not get into this lol
I've got the enum setup, but how can I choose it through code? Basically what I'm trying to do in the image
whoa, calling an Enum?
actually im gonna shut up cuz i dont know much about enums lol
Ah, right
Thanks mate, I'll go check UI Text and see how it works out.
So is there no way to translate 'int' to enum or vice versa
this is a question of my own, don't you need to like instantiate it or smth using like new?
I guess gameMaster.characterRace = raceSelected; if both of these are of the enum type
yes, you an cast Enum to int for example
just cast
Race selected is an int as I use it to scroll around a list
ur welcome, I suggest you use TMP so u have a lot of options later
Okay so you can convert one into another by casting it
ngl idk what casting means sorry for asking in parallel, im curious now
= (Race)raceSelected;
public enum Cardinal {Up, Right, Down, Left }
Cardinal dir = Cardinal.Up;
Cardinal dir2 = (Cardinal) 3;
int x = (int) dir;
this should give all the examples
Any way to make Unity alive again? I had infinity while loop that killed it
oh wait right, kinda like when u have
float someFloat = 6.4f;
int castedInt = (int)someFloat;
right
Yep
Force quit, restart
you must ask the opposite question -- if you have an infinite while loop then unity is stuck alive and you must kill it instead
cool, I just forgot what casting means then, I knew of this already ofc
ty :)
Yeah that is the way Im doing it now
close it. look at console logs to see where yoy messed up
was it a while loop
@earnest atlas task manager or alt+f4 is my go-to
isnt the whole point of coroutines is them being able to run in parallel?
if (!_isGrounded) // Double jump...........
{
if ((_rb.velocity.y <= 0f))
{
if (Mathf.Abs(_rb.velocity.y) > -0.01f && Mathf.Abs(_rb.velocity.y) < 0.01f)
_isGrounded = true;
}
}```
Well they arent.
wtf-
Cause a while loop in corutine made unity die
Im trying to disable double jump in the air
ah yeah thats the issue
nothing in Unity runs in parallel
overall while loops u have to be really careful with
or any loop really
like for loops are kinda more safe
true that, I kinda meant like
only loops you need is forloop
technically that'd still execute, would freeze unity a bit tho
just a normal freeze 🙂
not really true
sometimes you want multiple things to happen in a single frame
thats what whiles are for in Unity
for(;true;){}
all loops can be made from forloop
but you probably don't want to have a loop run every frame
likewise all loops can be made from while
Many times you do
well true, but its kinda about convenience
yeah but while stinky
well, not unintentionally, thats for sure
even the AI bot is telling me to use raycast...
having an if statement run every update is ok usually, if not inefficient
there's nothing inefficient about an if statement in Update
but a while loop without knowing what ur doing isnt the best
writing any code without knowing what you're doing is bad
having a lot of them can slow it down tho?
especially ones that only need to be checked in specific times
It's more about total number of operations than anything to do with the actual keywords used in code
true that, but a messed up if() is much better than a messed up while() lol
yeah that's what I mean
Wait it's that easy
like why would you check something like, idk, how much ur score is as an example every frame
yep
the question is, why is it not already of Type Races?
Sorry?
why is the raceSelected field not simply a Races field?
Also best practice for enum naming is Race not a plural like Races
no, the raceSelected field is not Races, why?
The fact that you need to cast means you used some other type... int?
Just make it Races directly
then you won't need a cast.
It's just a private int at the top outside of the void
why isn't it a private Races?
because I wasnt sure if enums could be used in the race scolling menu I use ints for
(also again that enum should conventionally be called Race not Races)
It is for ui i guess, and the order of enum is the same as display
you can cast to/from int if needed for something like that
Yes but I literally seconds ago put the enum in place
I think you joined the chat after they helped me
And once you change the order whole thing broken
On the right is my enemy. I have a fist (white square) parented to a fist pivot which is parented to the enemy body. The fist pivot has a collider on it, and the fist has a script that references that collider. On collision, it should send a debug message saying 'Hit' but it's not and I can't figure out why
Here's my code
It can most likely be changed, but it seems fine as it is because I don't really need to touch that part anymore, it's modular and should allow for infinite expansion
You need a Rigidbody2D for OnTriggerEnter2D
So would I need it on the fist or the fist pivot?
whatever is moving
also why punchTrigger as a class scope variable and a parameter variable?
Should I have the rigidbody set to Dynamic, Kinematic or Static?
in this case, i guess, kinematic
It keeps pushing my enemy back for some reason
It seems like it's because the fist is on top of the enemy body (In 2D). Is this not possible?
then your collider is not marked as trigger
I have made an end game screen for my 2d endless runner game, when the gameover function is called, i want to toggle my game over screen, i have tried using this and its throwing an error.
Omg yeah, thanks
and if this is the line the error is on then no GameOverScreen object is active in your scene
no, not there at all
in my start function i call gameoverscreen.off()
let me guess, that disables the gameobject?
and have you bothered reading the docs for FindObjectOfType?
What would be the best way to make the enemy check if the player is in front of them and if so, to attack?
But only if the player is in front and within a certain distance
I thought it was just used to call functions from other scripts
a physics query like a raycast, overlapbox, etc
try reading the docs sometime https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html
So it doesnt work on inactive objects?
Overlapbox would be used with a collider, right? and Raycast is a component I'd add onto the enemy and then configure with script?
And its inactive?
So i cant use it to call function but assign values or something?
this isn't godot where a raycast is an object in the scene. raycast and overlapbox are both types of physics queries that check for colliders in a specific area
did you actually read the page i linked?
Yeah i did
Yes but to use Raycast, I add it to the Enemy via the inspector, right?
no because it isn't a component. it's a method you call in your code
and you didn't find anything in there about finding inactive objects?
It doesnt return inactive objects
Would i just use something like this to call the function instead? myObject.GetComponent<MyScript>().MyFunction();
and you didn't find anything in there about something you can do to find an inactive object?
a serialized reference in the inspector would be 100% better than using FindObjectOfType
also use the component type for your variable so you don't need to use GetComponent
Ooooh
Can I make color.a value 1 transparent and 0 full color?
no. also why
Doesn't alfa exist for exactly that issue?
currently starts at red, want it to go red as it loses health
Its already red.
do some math
okay but why do you need the alpha channel to be 1 in order to be transparent?
instead of asking to completely change how color itself works, you should consider just changing the number you calculate...
1 - percentage will get the right number
although that does not account for the percentage potentially being greater than 1
Mathf.InverseLerp(1, 0, percentage); would properly clamp the result, as would Mathf.Clamp01(1 - percentage);
I'd just skip the percentage step
Mathf.InverseLerp(ogHealth, 0, health);
yeah that's even better
InverseLerp tells you what percentage a value is between two points
InverseLerp plus Lerp is basically a remap
What would i put as myObject?
How are you getting the reference to call .Off()?
i dont know, i just want to call a function from a different script
i am so lost
You said you were calling .Off in Start, right?
Yes
Right here
Yes its also giving an error
Ah, okay
So then you should read the thing boxfriend linked twice
okie
Would this be right?
to reference it?
Then i call gameOverScreen.Off()
What's the error say
A field initializer cannot reference the non-static field, method, or property
You cannot use GetComponent outside of a function
ah ty
You're very limited in what you can use in a field initializer.
i already have loads of references
why not just assign those in the inspector?
But this has gone red now
this is also not going to work anyway if the GameOverScreen component is not on this object
okie ill do it in the inspector
do i drag the script to the box?
there are no "scripts" in your scene. i don't like using that term
there are components attached to game objects
the page I linked shows exactly what to do
hey, there's an example of a short video that complements a written article!
love to see those
but how would i reference this? like public gameObject gameoverscreen?
Your script essentially becomes a component.
your script file defines a kind of component
always reference the type you actually want.
What type are you trying to reference
i just want to call a function from another script
that doesn't answer digi's question
So what type are you trying to reference
idk what type, game object?
Okay, what function of GameObject are you trying to call?
So do you want to reference your type or GameObject
right, so the type will be GameOverScreen?
bingo
Yes
then what goes at the end?
just public GameOverScreen ?
you have to give it a name.
The end of what
yes
ty
as would public GameOverScreen blorp;
gameOverScreen is a good name for the variable.
but I just want to point out that variable name doesn't matter
ah i got it mixed the other way around
additionally, game object names mean nothing
it doesn't matter what you name a game object; its type is always GameObject
right
similarly, it doesn't matter if you name your variable fooBar and also have a game object named fooBar
these are unrelated concepts
then how can i call it?
gameOverScreen.Off();
correct!
ahh thanks
assuming that you'ver assigned a valid reference
if you haven't, you'll get an exception
i wouldn't really call this "object oriented programming" stuff
I guess this counts.
But most of this has been about just declaring a variable.
yeah
copilot keeps suggesting this
do i need this?
no
or i have declared it in the inspector instead
if you want to grab a completely random GameOverScreen that may or may not exist, I guess
would i need this if i didnt use inspector?
It would be an alternative, yes.
i see
you should favor serialized references assigned in the inspector
they allow you to specify which object you want
right
and also make it very clear what a component requires
I do sometimes just use GetComponent when I know component A must always exist alongside exactly one component B
When i am calling other functions, its not bringing up error like it did for this
FindObjectOfType<ScoreManager>().AddScore(1); works fine
yeah, just mark those with [SerializeField] (if they aren't public) and then assign them in the inspector
and i never referenced it either
yep will do
its not bringing up error like it did for this
I don't understand what you mean.
Like when i tried to use FindObjectOfType<>.function, this brought up error
Because it failed to find
If it can't find an object, it returns null
You mean that an error happened at runtime?
yeah
Then yes, it failed to find an instance of the class
I thought you meant you got a compile error.
The runtime one
But when i add score it has no problem
Though i never referenced the script ScoreManager
Because that one is able to find the object
It doesn't matter if you've already assigned a reference in the inspector
You should still probably change that to a direct reference
FindObjectOfType<T> just searches the current scene for a T
It doesn't matter whether or not you have a variable that holds a reference to a T
okie
should i change all the functions i called using the FindObjectOfType<>?
bcause there is kinda alot of them
In general, you should avoid using any Unity function that starts with Find
okie
If you are using it, try to stick to doing it once
Grab the ScoreManager when you spawn and hang on to it.
just FYI you should switch to using the SceneManager API instead of using Application.LoadLevel
Sometimes it's perfectly reasonable to use
and oh man, I've never even seen Application.LoadLevel
no idea what that means
it's obsolete
so it may be removed in the future
notice the warning your IDE is giving you
ha, Application.LoadLevel is even just calling SceneManager.LoadScene now
https://github.com/Unity-Technologies/UnityCsReference/blob/2d4714b26573c9f220da0e266d62f42830c14ad6/Runtime/Export/Application/Application.cs#L436
you should switch anyway to ensure an update does not break your code though
note: you'll need to add using UnityEngine.SceneManagement; to use SceneManager
Your IDE should suggest this for you if you don't add it, though
And if you're ever unsure "where" something comes from, look at the doc page
im working on a game and im trying to come up with a simple and clean way to handle items. right now i have an item scriptable object with name, rarity, and type (weapon, tool, consumable, tile) but the thing is i want further classification like in tool i want pickaxe (with pickaxe power, etc), axe, and more. and when i left click with an item in hand i want to get exactly what type of weapon it is. idk if im explaining this properly but does anyone know an effective way to do this?
PlayerPrefs.SetInt("TotalDistanceTravelled", PlayerPrefs.GetInt("TotalDistanceTravelled")+1);
Does this work to increment the playerpref?
It doesnt look like a setter?
try it and see
it doesnt work
then why do you ask?
If you know it wont xD
how do you know it doesn't
it should work tbh
its not displaying
Also it looks a lot like Database request for data
thats why i ask if it should work
show where you display it
and where do you call it
and what does the text display
did you log the saved int?
what does it display
i call it after the game ends
is this being called at all?
please show 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.
everything that includes that system
Is there any VSstudio plugin to work better with unity? For some reason method names are not highlited?
wdym
make sure it is configured 👇 !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
https://pastebin.com/PvAXa60g
https://pastebin.com/s2311VVR
warning about this code btw
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Its completing things like functions and such of unity. But methods nope
wdym "methods nope"
learn how to ask questions please
Like start,awake,etc
what about them
wdym, they nope
Not autocompleting at all
in what context. because it works perfectly fine for me
do you know why it doesnt work?
In when you want to call some unity method like:
Update, start, Awake, OnTriggerEnter, etc
call them?
I mean this
thats not calling a method
Im not native eng and have absolutly no idea how to call that
how to call what? you are not calling any function here
What im doing then
looks like you've got some compile error that you need to fix so that it can realize what you are actually trying to do
I do not
Your !ide is not configured properly then
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
you do - that's why void has a red underline
it is configured
Show us your console
mouse over the underline and show what it says
Its considering that void Upda as incomplete
So its complaining about missing semmicon
The first error I believe translates to "unexpected token void" something like that?
yeah because its reading next line
Make sure intellisense is enabled: https://learn.microsoft.com/en-us/visualstudio/ide/using-intellisense?view=vs-2022#intellisense-options
why does one of em work...? i simply js switched the order..
that line of code is impossible for a human to read. Break it up
That's unreadable.
how do I make a AI navigation that is able to play animations (attacks) every now and then ifykyk?
jezus what is that monster
You don't get bonus points for putting everything on one line.
playing animations is unrelated to moving around
i am unclear how this is an "if you know you know" situation
Your actual compile issue is you closed the parentheses )) and THEN put && !attacking but it's really hard to notice that since the line is so long
but if you look at the game Muck and their AI it attacks every now and then
there, broke it up
and thats what im trying to get for my VR game
oh thanks
this isn't really breaking it up
I think it is working?
Breaking it up would be:
bool isMoving = player.velocity.magnitude > 0;``` ^to replace all the player velocity checks
and then using isMoving in the if @scarlet skiff
that's one line of code that's been hit with a hammer
cache that Mathf.Abs pls
break out chunks into separate variables
then you can do a big a && b && c && d at the end
why does collision not work when animation is running
please see #854851968446365696 for what to include when asking for help
even better
omg that &&
id need one of moving in 7 axis, and one if moving in x axis, and even those lieki need one if moving up, one if moving down etc..
this is certainly more readable than mashing it all onto one line
but I have trouble parsing what some of th ose lines mean at a glance
elaborate pls
you have so many Find calls in this code i'd bet the playerpref is never actually being set due to runtime exceptions like NullReferenceExceptions when Find doesn't actually find the correct object
storing them into a variable with a descriptive name would be superior
i thought my code killed you
yeah even 1 nullreff kills the script 🙂
okie i will try clean it up
when my 2d stickman idle and walk animations are running, collision doesnt not work, is it because the rigidbody component gets disabled when animations are running, since it also configures the transform
yes that is precisely why
instead of doing 2x Mathf.Abs(player.velocity.x) and 2x for y, you can just cache it in a variable then use it, simplier and cleaner
This is a tutorial on game programming patterns in Unity with C# code. Another name for the same thing is software design patterns. You will learn the following programming patterns: command pattern, and much more. This section is all about the state pattern.
how could i prevent that if the changes are beyond the properties
what does that even mean?
if you are disabling your rigidbody then you need to not do that
i cant just press a button to stop it
im not
physics is
maybe
don't make assumptions about what is happening and pass them off as something you are doing
im afraid im unfamiliar with "cashe" 😬
i look at the collision while the project is running, it does not get visibly disabled, nor does the rigidbody gets visibly disabled
store it in a variable
to cache is to store something and re-use its value
and then use the variable
So then why did you say the rigidbody is getting disabled
then why would you say it is.
Is there a way to easily sort out animations? (My game automatically moves to the right soo it is always running except when playerspeed is set to 0, then its idle) i cant use keypresses as the game will be managing players speed
there's a nominal performance benefit, but it also just makes the code easier to read
bool splinesReticulated = // Horrifically complicated code here
if (splinesReticulated) {
...
}
animator.SetBool(Mathf.Abs(player.velocity.x) > 1 || Mathf.Abs(player.velocity.x) < -1)
could be done cleaner by caching the abs value
float absValue = Mathf.Abs(player.velocity.x);
animator.SetBool(absValue > 1 || absValue < -1);
Why not just make a parameter that has your X and Y velocity, and use the Animator window to determine which animation to play based on those values
let me word it this way, i think, the rigidbody does not run the physics code, when the animation is playing, because they both configure the transform, and i want to play the animation without losing its collision
thanks ill keep this in mind
thanks!
your animator is overwriting the position set by the rigidbody. it is not disabling the rigidbody or making physics not run, it's just overwriting it by controlling the position manually
This looks like you've made one boolean for every single animation state in your animator and then setting it based on a convoluted confluence of variables.
Why not just use the Animator as it was intended and put these conditions on transitions, and feed in things like your velocity and various other booleans as parameters those transitions can read?
If your animation is modifying the root object's transform, it shouldn't be. You should be animating a child object of the actual thing that's moving around and doing the colliding
so how could i preserve the collision?
but it could be either code or editor extensions too... i'm doing all by code with imgui
this converstaion has been going on for what seems like weeks @scarlet skiff
it's editor code. therefore it is #↕️┃editor-extensions
the animation only configures the transform of the limbs, not the parent. which also explains why when i tried to debug the issue, the box collision inside the parent worked, but the box collision in the limbs didnt
wouldnt that need like a LOT of transitions? and wouldnt u then kinda get lost, if there is a problem with an animation, id just look at all the conditions since they are all in one place and id fix it there
by "collision" do you actually perhaps mean OnCollisionEnter/Exit messages rather than actual physics collisions?
Perfect!
regarding what exactly
Each animation state would require one transition for each other animation state that this state can change into.
i mean that my character just goes through the floor
your refusal to use the Animator correctly and digging yourself deeper and deeper into a hole
This is literally what the Animator was designed to do
it replaces the legacy animation component because doing it the way you currently are is absolute fucking misery and no one liked doing it
well then it's because you are controlling the position of your objects using the animator instead of moving them in a physics friendly way. this is not code related so you can ask for help in setting up your animations in a way that still allows physics to work in #🏃┃animation
if you have jus ta few animation that does become a lot of transitions quickly tho
You have like six animations and your code had to be rewritten like six times before any of the people here, some of whom have been programming for literal decades could even read it
Stop caring about having a dozen transitions
from what i have understood when you get a lot of animations you could benefit from calling them frm a script rather than a transition, and for me its working fine, it was a simple syntax error that i didnt notice that was the source of this problem, sometimes you need a fresh pair of eyes, considering i most likely wont be adding another animation, i think i did fine
Ask yourself this question, 'If my was was better why am I still having so many problems with it?'
Any good tutorial on layerMaks for raycast
why would there be a tutorial for that?
the answer was apparently a syntax error so ye. Not saying its better it just works fine for me. Only had 1 major issue and it was with logic, and considering id use the same logic for transitions, i dont think it could have been avoided, but i cant be sure i suppose
My rb2d.velocity.x is 0 when the player is moving, whys this?
how is it moving
transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f);
oh is it because rb2d is not moving it?
that doesn't use velocity. it doesn't even use the rigidbody
Well, yeah. You're teleporting the object. That doesn't use the rigidbody at all
how would i move it using rb2d?
Either AddForce or set the Velocity usually
yeah just set the velocity to playerSpeed
ok
or rather a Vector2 using playerSpeed as the X axis
bits
yes. or you can just do it the sane way and create a LayerMask variable and just assign it in the inspector. no bit shifting required. don't even need an understanding of bitmasks for it
yes
Nononono sane me.... rubber room with rats... rats made me crazy....
i mean.. its 8 animations, would be 36 transitions, but idk i mean those same transitions would also have logic in a script so mgiht as well call them from there...? idk bro
Can every animation transition into every other animation
with very few exceptions
Then you'd need 8 transitions
but good point
i totally overlooked Any State
thanks, ill keep you points in mind for the next project
man, I told you this on day one
For some reason the buttons in my main menu don't work, all of them have on click commands and don't work. there is one button with no on click command that works but I don't know why
float hitData;
if(Physics2D.Raycast(transform.position, _rayDirection, out hitData, 10, _groundLayer)
{
}```
Any idea how to output hit data in same if?
figured out the issue
hitData is not a float
This code does not compile
I know that, Im just looking at one guide
don't, look at the docs
its not docs
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hitData;
if (Physics.Raycast(ray, out hitData, 10, layerMask, QueryTriggerInteraction.Ignore))
{
// The Ray hit something less than 10 Units away,
// It was on the a certain Layer
// But it wasn't a Trigger Collider
}```
This guide online has if outputing hit data
tho its 3d
so where do you see hitData declared as a float in that?
Issue its declared nowhere and I have no idea what is it
what?
float hitData;
I was just guessing
figure out which one you're suppose to use. the first example you posted uses Physics2D.Raycast, the second example is Physics.Raycast. they have different overloads . . .
look harder. it is declared there
don't guess, LOOK AT THE DOCS
there was a comma in there you apparently missed
happens a lot
It is declared
it's in the section you've posted
it's right there
Could I insert a new material into Material[] with code?
Im blind
not that the Physics.Raycast code they posted is going to be useful anyway since they are trying to use Physics2D.Raycast which doesn't have an out parameter
Arrays are fixed size. You cannot change the size of an array at runtime. If you're going to be adding to it over time, use a List
this is the answer for me yay
Right, but still, it is there
oh i know. i pointed that out to them already
no, the answer for you is to read the fucking docs mate. you would have seen how to use it if you'd bother spending any time actually making an attempt at understanding instead of guessing then immediately coming here
Ive looked up a guide that had that code I came here when my tries to make it work DIDNT WORK
RTFM, how many times must you be told!
you looked at a guide for a different method, assumed it would work for the actual method you are using instead of literally just looking at the documentation, then came here when the code for a different method doesn't work for the one you are using
Ive came here mostly cause I thought I messed up "out" cause I dont tend to use it at all.
and had you bothered reading the docs you would have seen you didn't need it at all
I wanted to use fancy out considered I rarely use it I though I messed up with it
try
{
if (_isJumping) // Jump logic
{
var hit = Physics2D.Raycast(transform.position, _rayDirection, 2, _groundLayer);
if (hit.collider != null)
{
if (hit.distance < 0.36f)
{
_rb.AddForce(Vector3.up * _upwardForce, ForceMode2D.Impulse);
}
}
}
}
catch (Exception e)
{
Debug.LogException(e);
}```
Randomly player starts jumping much lower then he should. Any idea what can be the cause?
What's the expected height and what's the actual height?
And when do you call these lines of code?
FixedUpdate
Other than that, when do you reset jumping state?
Is there a possibility that you're jumping more than once sometimes? (or less than once sometimes)
Exepected on left, bugged on right.
Set the jumping state to false after jumping?
I want my game object to only spawn once, but it's spawning multiple times. https://pastecode.io/s/acyrxrce
void OnEnable()
{
GameController.Instance.PlayerControls.Enable();
GameController.Instance.PlayerControls.PlayerControl.Movement.performed += OnMovementPerformed;
GameController.Instance.PlayerControls.PlayerControl.Movement.canceled += OnMovementCancelled;
GameController.Instance.PlayerControls.PlayerControl.Jump.performed += OnJumpPerformed;
GameController.Instance.PlayerControls.PlayerControl.Jump.canceled += OnJumpCancelled;
}
void OnDisable()
{
GameController.Instance.PlayerControls.Disable();
GameController.Instance.PlayerControls.PlayerControl.Movement.performed -= OnMovementPerformed;
GameController.Instance.PlayerControls.PlayerControl.Movement.canceled -= OnMovementCancelled;
GameController.Instance.PlayerControls.PlayerControl.Jump.performed -= OnJumpPerformed;
GameController.Instance.PlayerControls.PlayerControl.Jump.canceled -= OnJumpCancelled;
}
private void OnJumpPerformed(InputAction.CallbackContext context)
{
_isJumping = true;
}
private void OnJumpCancelled(InputAction.CallbackContext context)
{
_isJumping = false;
}
unity input system. Class is generated in another constant singleton script
Why Im calling it each time? Because it decided that its not gonna link any other way
I'm assuming that you're applying force more than once - have not been made aware of when jump state resets yet.
Bumping this
So you mean my expected jump is like 3times stong as it should?
Try logging to see how many times jump was fired
Yes, I formatted the code
No, force is applied only once
2 jumps and only 2 times code was called to apply it
Maybe change the if condition to when true and set it to false insidecs if (Spawn == true) { Instantiate(puyo2[puyotypeIndex], new Vector2(-12.5f, 5f), puyo2[puyotypeIndex].transform.rotation); Spawn = false; dropSet++; }
Can you show the logs?
I'm confused as to why you've got a try-catch. That's concerning
I had some weird issues that contols just stopped working
I though it crashed somewhere on jump
so I added that
Why don't you go follow a tutorial, anthony? There's bunch of tetris like tutorials and it's probably worth it if you keep getting stuck on this one script
one sec adding log. I had break there
Every time you collide with anything while Spawn is false, you spawn an object.
When you collide with any object in the first five layers, Spawn becomes false until the end of time
Yeah its correct.
Meaning once you collide with something in those layers, every other object you collide with causes a spawn
Let me rephrase that, I want it to spawn when it touches the same gameobject or the ground.
Wait no its called twice?
Also learn how to use && and ||
Great now I need to somehow fix that
Consider resetting the jump state to false after jumping
You can have zero to many fixed update frames between every update frame.
Assuming button cancel occurs on Update and not fixed update
Cancel happens on unity input
Its just fixed update happens twice while player is on the ground
Im just making a corutine
Which is either update or fixed update.
No idea
The new input system should have means to control this
Assuming you did not configure it, it's on update
private IEnumerator Jump()
{
Debug.Log(DebugJump++);
_rb.AddForce(Vector3.up * _upwardForce, ForceMode2D.Impulse);
yield return new WaitForSeconds(0.5f);
_coroutine = null;
}```
This should probably fix it
Meaning, you could have told it to jump in update and had no jumps or many jumps (undefined behavior either way)
if (hit.distance < 0.36f)
{
if(_coroutine!=null)return;
_coroutine = StartCoroutine(Jump());
}```
You still might not get any jumps at all..
it can jump at best every 0.5s
Hi all, what's the best way to save basic variables so they can easily be accessed by other scripts.
Update 1
isJump = true
Fixed Update 1
Jump()
Update 2
isJump = false
Fixed Update 2
Fixed Update 3
Update 3
isJump = true
Fixed Update 4
Jump()
Fixed Update 5
Jump()
Fixed Update 6
Jump()
Update 4
isJump = false
Update 5
Update 6```
What do you mean by "save"? Like in a save file?
I intent to implement that after, but just say store for now
So i need to set jump to false?
Just set it to false after jumping to get consistent jumping.
I don't understand. What variables am I supposed to make = false and true respectively?
Setting it false made it worse 🙂
I'm simply pointing out what your current code is doing. Essentially, once you've collided with any object on a layer 0, 1, 2, 3, 4, or 5, you set Spawn to false, which means that from that moment on, every single time OnTriggerEnter2D is called, it'll spawn a new object
Someone call an exorcist. I cant take this anymore
Increase the force. It should not be occurring more than once per jump input now.
One jump is short, other is long, next 3 short, long short long no jump yes jump
So I should put it in start?
I wanted to make Player to be able to auto jump
Consistency is what you ought to be aiming for.
You need to decide when you actually want to spawn the object
Well thats exactly whats got worse 😄
Under what conditions should something spawn
If it's touching the ground or the top of the same gameobject.
Define "auto jump" 
What do you mean by "the top of the same gameobject"
An object cannot collide with itself
You dont need to press jump repeatedly jump to continue jumping
as I had it before it was working like that
Thank you 🙏
I had vector3 in the force multiplier. Lets see if it fixed that
I meant a clone of the object.
and I instantly fell in the void
Okay, so, any time an instance of this object collides with the ground, or another instance of this object
Yes
it's absolutely bonkers that you decided to record a vertical video on your phone to demonstrate this issue instead of just a few screenshots. it is also basically impossible to read the code in that video. but you need to go through this: https://unity.huh.how/physics-messages
Should probably google about how to approach small, medium and large jumps 
Assuming you're wanting button held down to apply higher jumps
Okay, and since all collisions inherently happen between two objects, when two of these objects collide into each other, you want them both to spawn one?
No i dont. I want it just to jump with constant force and not this random Lottery of jumps
Acquire jump from the button down and reset it after jumping...
Thanks for the feedbacl!!!
