#💻┃code-beginner
1 messages · Page 425 of 1
i wasn't trying to "roast" you. i was hoping that would help you realize that you were still fucking misusing those random number generators. they were not meant to be used in that manner
and you insist that they are wrong because you misused them
To be fair, Lehmer algorithm is not considered a hash function. It's considered a random number generator.
https://en.m.wikipedia.org/wiki/Lehmer_random_number_generator
I insisted that they're just not the tool for it, seriously
I said weakness as they do their job normally, but not for this
yeah and again "this" is just attempting to misuse them. you had a bad implementation so they were showing similarly repeated patterns because your implementation with your attempt at using them was just wrong
We're just a bunch of people that none wanna yield, that's the ironic part here
All the same, all just defending and yeeting eachother 😂
Not accusing anyone, as it means that it's the same for myself
But it's just hilarious
it is absolutely possible to generate consistently random numbers using seeds and not get repeating patterns if you don't implement it like a caveman going "unga bunga me hit rock with rock, it make other rock"
Just how many arguments are you gonna try against me after so many that I can counter?
My bad... I guess
I'll check it later
Boxfriend, thanks for the recap of what you've said so many times, however I said so many times too that I was asking for something else, and I was suggested by dlich to use them for this purpose, which was totally not where I should've been using it.
your counter argument is essentially not actually understanding what anyone wrote to you, and then claiming we're all the same. What we wrote above is not matter of opinion, the tools can be used properly to work. You simply dont understand the fundamentals of randomness or hashing. Multiple people are telling you this, yet you're wording this as if its an opinion on how prngs work.
I've proven that there's a way I can do it, so I wasn't asking for something that don't exist.
I've been asking for something generating a prng with a non-random looking number
I've asked twice to prove me, whomever here, make a function that takes in x and y, and output a random looking value, always consistently the same when fed the same x and y
And all I got is accusations that I was using the tool wrong, while I tested it since y'all are in denial since I didn't bother testing them before
What should I have been doing, then?
The only issue here might be that I toke hash for the term to use here, while I technically needed a random number generator, but that was at the beginning, and should've been long clear after so many mentions of random numbers
so I wasn't asking for something that don't exist
Your initial question was infact something impossible. The algorithm you used cannot solve the original question. Because people had to force more details out of you, it was eventually realized the original question wasnt what you wanted.
If you dont think the original question was impossible, then try it out. Try to use any function in the world to take 2 ints and represent it by 1 unique int for every possible combination
I'd also like to point out that your "seed" calculation is playing a huge factor here. generating seeds from that from (-10,-10) to (10,10) provides reused seeds 50% of the time.
The initial question was in fact possible, too, like dlich suggested, one example simply is to do x + y * width
And I could've used that, indeed
But feed it into what kinda prng function?
Sigh, forget it, I get the message that you're just gonna insist on the same point after all explanation
Honestly it doesnt look like you're fully reading what i wrote. The initial question, meaning the first thing you posted before anyone had to pry more information out of you, is impossible to solve because your question was essentially "how can i fit 2 ints into one"
I'm out, bye
By allocating 8 bytes
There's that feature.
I'm out fr
rofl, you have got to be joking
It's called a long, have a nice day.
i didnt even realize this myself, wow
Shift x by int byte count, perform & with y
yes it is so is not 'fitting 2 ints into one, is it?
I can't deny that it could've been confusing, I did try to show the issue by giving examples of ways to fit it together, and the repetitions it causes.
I'd like to point out that after all present issues are over, I get attacks using the past issues.
Can you deny that you're just picking on me using whatever you can find?
Stop pinging me for today, seriously.
I'll do better than that, I'll block you
private float dissappearTimer;
private float maxDisappearTimer;
private Color color;
private SpriteRenderer spriteRenderer;
private void Start() {
spriteRenderer = GetComponent<SpriteRenderer>();
dissappearTimer = 0f;
maxDisappearTimer = 1f;
color = new Color(1, 1, 1, 1f);
}
private void Update() {
dissappearTimer += Time.deltaTime;
color.a = Mathf.Lerp(maxDisappearTimer, 0f, dissappearTimer / maxDisappearTimer);
spriteRenderer.color = color;
if (dissappearTimer >= maxDisappearTimer) {
Destroy(gameObject);
}
}
public void SetColor(Color color) {
this.color = color;
Debug.Log("change color");
}```
Hello, so this code works, but the `SetColor()` does not. For some reason `this.color` stays white. I have checked with a log wether the method actually gets called, which it does. The paramater in the script that calls is just `SetColor(new Color(1, 0, 0))` so I dont think that should be the problem. I have no idea why the color wont change :/
you should log what the color being assigned actually is
Oh yeah, good idea
instead of your mostly useless "change color" log, do this: Debug.Log($"Color changed to {color} on {name} ({GetInstanceID()})");
Color changed to RGBA(1.000, 0.000, 0.000, 1.000) on RadarPing(Clone) (-203216) welp, this is what I got which means the color is changing to red
Are you looking at the correct clone? Which clone is the one not changing?
you saw that log with different numbers at the end for each of the clones, right?
because each individual one will have a different InstanceID
Correct
When are you calling set color?
If its before start runs, you're overwriting the value in start
Place a comma and this after the string message with debug:cs Debug.Log($"...", this);
I instantiate it, then I set the color
yep, that'll be before Start
When? Immediately?
You were right, I just used Awake insted of Start
honestly that line in Start can just be removed. you can assign the color in the field initializer so that ones you spawn without assigning a color to will still have the color set to white without your SetColor code being overwritten
Yeah I wasnt sure if assigning it that way was a bad practice, so I am used to initializing variables in Awake() or Start()
It's perfectly fine, as long as you are aware the values set in inspector will not be overwritten when you change the value in the field initializer (which is a good thing).
Aight thanks :D
when I press q it steps normally but still sometimes dont go forward, this is my code https://paste.ofcode.org/w2P6yWCZzkVH9xXRSYSAYU
but when I press w after that
its like this
so I cant move forward
limits are like this
A video could help
I already got it from a video that imitates qwop just without ankles, tried to make it easier
I have these blocks of information that contain the name of the object type and slots for them and I want to organize them in a vertical layout group, however, when it comes to spacing the slots overlay the next component in the layout group, how can I make sure that it keeps the spacing regardless of the number of slots??
Oh I meant a video recording of your issue
like this
When I add spacing but then are more slots, they still overlay each other
Use mp4 please so it embeds into discord
More reliable format while recording
The joint motors seem to be working fine
It just seems that the other foot is pushing it back
Should probably try bending the back foot when the front foot is pulling from front to back
Like humans do
Another hack is to make the back foot's friction 0 when it is moving forward
So it doesn't stick to the ground and mess it up
where can I change its friction
Create a PhysicsMaterial2D and assign a it to the Rigidbody
It has settings for friction and bounciness
I think the probken is that the size of the group doesnt depende of the slot number but still, I need help
Make sure that the feet have different physics materials so you don't edit both at once
I forgot I could assign physics materials not only to ground but to the limbs
Looks like the friction hack would solve this
should I make its friction always 0 or on a condition in the script?
I would have high friction on the foot that is pulling you forward
And low on the one that is not supposed to move you
In other words, use low friction for the foot that is moving from back to front
okay thanks
So yeah you have to script it
is there a way of resizing it?
is there any way i can reference a SO in another script so lets say i wanna use the fireRate of this particular SO and yk use it for the guns firerate etc but im not sure how i can reference it into another script since its a SO
So I have a player that jumps as long as it doesn't collide with an object. On touch, it disables a bool that allows the player to jump, so it can't jump anymore. The problem is that after several seconds the canJump bool is set automatically to false and I don't know why (there are the script where I only use that bool)
the same way you reference any other UnityEngine.Object type
if anything causes that OnTriggerEnter2D message, the player will be prevented from jumping
so should I use tags ?
you should check what was collided with, yes. and in doing so you can remove all of that stuff from Start since you won't need it, you can check if the correct object interacted with the trigger then get those components from that object
yeah but dont i have to make a gameobject in the scene then put the WeaponsSO on that gameobject as an component?
no, a scriptable object does not get attached to a gameobject
refer to the scriptable object directly using the Serialized References section of that link i sent
im a bit confused on which one i gotta check
it turned out to work, i realized immediately where the problem was, thanks
just look at the first one
and consider going through some beginner unity courses if this is all too unfamiliar for you
I have these blocks of information that contain the name of the object type and slots for them and I want to organize them in a vertical layout group, however, when it comes to spacing the slots overlay the next component in the layout group, how can I make sure that it keeps the spacing regardless of the number of slots??
Everytime I add one slot (because it is going to be expanding) it overlays the rest of the elements of the grid
in terms of hierarchy, I have the grid as a parent of the group which has a text indicating the category of the object and a child grid of slots
Wait, so it's a grid or a vertical layout group?
the GloveInventory is a vertical layout group
that contains a text and a grid
sorry, I might have said it wrong
This VLG has a grid that fits three horizontal slots?
VLG has as child objects: a text and a grid that (what I want) fits as much slots as possible (it is expanding)
the thing is that whenever I expand the slots, the next group in the VLG is overlayed
Are SOs terrible to modify? Like should I not be modifying the information on an SO and they should be strictly storing?
there are differing opinions on that. If you do want to modify a scriptable object at runtime you'll need to be aware that it works differently in the editor than it does in a build, if you modify any serialized fields on a scriptable object in the build editor those changes will persist (assuming you are modifying them on an asset and not an instance created at runtime), but those changes do not persist in a build. this is because you are actually modifying the asset
a lot of people will also tell you to use SOs as data containers and not to modify them, but as long as you do it smartly (such as only creating instances at runtime and modifying those instead of modifying the assets, or properly resetting your changes to the asset) and you understand the differences in how modifying them work in a build versus the editor then it's perfectly fine to modify them.
I personally use a scriptable object to hold a bunch of data that is modified each time a level is played because it holds data about which map, the difficulty, and the enemy. I also always reset it before applying that data so i know it is always in the state that i expect when i go to use it
I think that it doesnt take in account the size of the group itself
Thanks boxfriend thats helpful
The consensus is you shouldn't modify an SO because of the unwanted behavior. As boxfriend stated, changes to the SO persists in the editor but not in the build
You can modify them, but only if you know what you're doing. This is done by creating instances of the SO during runtime, as any change to these will not present because they are not assets in your project, but you have to manually manage (release) them. This is smth people overlook and improperly acheieve . . .
because the slots are going to be expanded at some point
Okay so in the editor I should make instances and edit and play around with those and in a build I can just use the direct asset? Is that kind of what you’re getting at
Do you have a content size fitter on the VLG to expand when needed?
yes I do
If you spam duplicate the slots, it should add them correctly with the spacing and GameObject beyond the size of the VLG . . .
it doesnt, look
I duplicated slots and it doesnt separate
To avoid modifying the original value(s) during playtesting, you can create instances of the SO or write a Reset method that resets the SO to its default state (values) . . .
how do i get the start function back on my script
Wait, so is the overlayed — 4th — row supposed to be under the top or bottom Resources group?
if you modify any serialized fields on a scriptable object in the build those changes will persist
You meant to type "in the editor" here, right
Huh? Just type it . . .
oh okay
just separated from the other group
Code is written with the keyboard.
Or ask ChatGPT to make an empty Start function for you 🧌
You can write, add, or remove any method you want. It's your script. You have all the control. Place them fingers on those keys and code!
bet
It just has to be separated one group from another
I know but I can't understand where this row is supposed to be. At the very bottom or in the 4th row. It's confusing because there are two Reources texts . . .
What is the hierarchy or layout? Does the VLG consists of the 3 horizontal slots?
Does anybody know how is the menu called and what is its route if i want to reference it like this:
[MenuItem("Edit/Project Settings/Tags and Layers/Get Layer Names", priority = 50)]
I would rather ask in #↕️┃editor-extensions
Alr thx
Are you gonna move the question there because I have some answer/clues for you
this is my idea
and when it expands I want it to keep some separation
The problem is that when it expands it doesnt keep the separation
this is what I get when it expands
{
while (true)
{
yield return new WaitForSeconds(spreadInterval);
List<Vector3Int> newlyAddedPositions = new List<Vector3Int>();
foreach (Vector3Int position in positionsBeingProcessed)
{
List<Vector3Int> targetPositions;
bool canFlowDown;
if (TryGetValidNeighbours(position, out targetPositions, out canFlowDown))
{
ProcessFlowDirections(position, targetPositions, canFlowDown, newlyAddedPositions);
}
}
foreach (Vector3Int pos in positionsBeingProcessed)
{
fluidCells[pos] = GetOrCreateCell(pos);
}
positionsBeingProcessed.Clear();
positionsBeingProcessed = new HashSet<Vector3Int>(newlyAddedPositions); // Overwrite posBeingProcessed with all newly added positions
Debug.Log("FluidCells: " + fluidCells.Count + " Being Processed: " + positionsBeingProcessed.Count + " New: " + newlyAddedPositions.Count);
newlyAddedPositions.Clear();``` i thought that these lists were overwriting eachother. but even after adding the .Clear() i still dont see the counts go down in the debug.log
You have 2 Clears, what counts don't you see going down?
I have these blocks of information that contain the name of the object type and slots for them and I want to organize them in a vertical layout group, however, when it comes to spacing the slots overlay the next component in the layout group, how can I make sure that it keeps the spacing regardless of the number of slots??
neither positionsBeingProcessed.Count or newlyAddedPositions.Count go down
after running out of positions to spread to the lists still have the same amount in them. + i guess theres something else going on since they seem to be passing a position back and fort at the end
Well,
-
positionsBeingProcessedwon't be cleared, because you create a newHashSetafter clearing it.
positionsBeingProcessed = new HashSet<Vector3Int>(newlyAddedPositions);
-
newlyAddedPositionswon't be cleared, because you log it before clearing
but shouldnt List<Vector3Int> newlyAddedPositions = new List<Vector3Int>(); clear the old list?
This can be achieved using Grid Layout Group
It doesn't clear any List, it creates a new one
Sure but you are creating a new one right after that and filling it with newlyAddedPositions
"Resources" is my group of objects that contain Text and the grid layout of slots and GloveInventory is the VLG
Well yeah, technically doesn't clear it but creates a new one
and it doesnt work
Define "doesn't work"
this is what I get when it expands
so instead of clearing the lists and refilling them i keep generating new ones?
it doesnt take in account the slots
That's what new does, ofc
This is the same you have previously shown as your objective
You just have 2 slot containers
What does this mean?
If you want several slot containers to consider each other's height, put them inside of the same parent
They are
You're generating new Lists, because you're not using an already created variable
List<Vector3Int> list = new();
while (true)
list = new();
But creating a new one every loop
while (true)
List<Vector3Int> list = new();
Note that there is no type specified in the 1st variant, List<Vector3Int>, meaning that it already exists
the I add the slots:
this is the process
Here, both Resources have to be pinned to the top
What? Both of your code versions create new lists.
Note that there is no type specified in the 1st variant,
List<Vector3Int>, meaning that it already exists
- 1
list = new();
- 2
List<Vector3Int> list = new();
In the 1st variant, the already existing variable is being used
Both one and two create new lists.
You're just using an implicit constructor in the first one.
In both.
I still get this
Does the 1st variant create a new variable? So that there is a new variable each loop
First one assigns a new list to an existing variable.
Yes
So there is a new variable every loop?
If you wanted to reuse a list, you can clear it and keep on using it. list.Clear()
right now i made the list a class variable and just calling clear() at the start of every iteration
that seems to work fine
In your code, yes.
It does not create a new variable. Is creates new List and assigns it to the existing variable
These are different
It creates a new value
That's the same as
myOldList = new() { 1, 2, 3 };
There is no difference. What you have is a reference to the list.
When nothing is assigned, it's null. Every call to new creates a new object and assigns it's reference to your variable
That's how reference types work.
Variables represent storage locations.
If I add the slots one of the groups overlay each other
No dlich is right
It assigns it to the variable, but doesn't create a new one
It's a different memory address essentially
Reference types represent a reference to an object. Value types are stored directly in the field.
That's why myOldList, and not myOldList2 is used
There two separate objects but can have the same values
new() just gives a new reference to the class
Yes, it assigns it. But assigns what? That's right, a new list.
What are you trying to accomplish feel like we're getting off topic
So, what does it assign it to?
#💻┃code-beginner message this stems from my question
what should I do?
Oh what lmao
To a reference. A 8 byte variable representing the address of the object.
From this pic, the top looks like a grid layout (third row added). I assume you want a VLG for each group of slots (that are associated with a text label)?
Support me in this discussion
If you don't believe me, maybe you would believe the docs:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/new-operator
YES
It assigns a new list to a variable, which already exists. It does not create a new variable, but reuses an already existing one instead. That's the reason no type has to be specified
Well, that's what I've been saying?
But the VLG group has to be made up of groups of text AND the slot grid
But I dont manage to get it done
But you don't care about a variable that already exist. You should care about a list that potentially is a lot bigger than your variable. And the old one is gonna be collected by the GC for nothing.
I don´t think it is a code begginer discussion tbh
It's pretty basic C# stuff tbh.
What do you mean by "you don't care about a variable that already exists"?
When no parameter is specified, a reference or a value, depending on the variable's type, is assigned to the variable, which does not create a new variable, only a type
Okay, I did not know the VLG group was a group of slots with the label. Now I understand . . .
When you assign the list a new instance, you're no longer working with the previous list but a new instance - clearing the list before assigning it a new reference isn't useful at all unless you're referencing it elsewhere. The new list is given a different list as an argument in its constructor call - it isn't empty at all but a copy of the list that was passed as an argument.
Imagine a box of apples - that's a list. You put it on your table - that's assigning it to your variable. Then you throw the whole box into the garbage and bring out a new box with apples - that's you assigning a new list. The old box is gone and wasted.
the VLG is the parent, that contains several groups of a prefab that contains: label and grid of slots
You guys are saying the same thing pretty much lol?
i got that from the ongoing discussion here:p now i made the list a class variable and calling .Clear() at the start of every iteration
Not at all. They're claiming that there is no new object created when using new and the old object is not GCed.
Let's translate it into coding.
You have a List of Apple, List<Apple>, in your class, ClassA.
You put it on your table. So, you put List<Apple> from the class ClassA to the class Table? A whole variable? I'm not sure whether it's possible in C# during runtime. You can only assign its reference or value
When you call new on a existing variable the old one is Def getting gcd
You don't need to translate it to coding. I specifically made an analogy so that you can understand that using new is a waste in that scenario.
Well, we're talking about coding, not apples, don't we? That's why I've translated it into coding
Your grid is overlapping. Make sure the container (parent) holding the grid has a content size fitter so it can expand . . .
I have said this whole time that a new object is created when using new...
We already know the code though. You shared it earlier. We're talking about that code.
I already have it
the problem comes when I add slots to the grid of any of the groups that contain the label and the grid
The location of the box of apples is not changed when using the new operator.
It's that the apples inside of the box are changed
Yes. That's correct.
new creates a new type. It does not create a new variable.
A new variable is created in this case:
MyVariable variable = new();
But not this:
variable = new();
An object of type MyVariable is created in both cases
It doesn't create a new type. It creates a new object of that type.
Right, that's what I meant
You seem to be thinking that I'm talking about declaration of a new variable. That's not what I'm talking about.
I'm not understanding your new variable argument. They are working with a new instance each frame regardless of what scope the variable is defined.
Well, that's what we've been talking about the whole time
No lmao you guys were arguing different things
Not me. I've been saying that a new instance is created in both cases.
But that's why I said your both right?
Right. I guess I misunderstood what they meant. Off to bed.
I'm saying that:
-
- Reusing an already existing variable does not create a new variable
myOldVariable = new();
-
new()does create a new object of type, regardless of it being reference or value. But it does not create a new variable
If I'm right, and he's right . . . then you're right, right?
Yes, that's the tricky part. It's all about setting up the hierarchy, child settings (for layout group), and content size fitter correctly. I may have to create a quick example. Need to finish showering first . . .
yeah, dont worry, It would be very helpful
What about your grid layout? The container for that should have a content size fitter . . .
it has
the thing is that it doesnt take in account the slot grid when making the space between the groups(that have label and grid)
@ionic zephyr
Group (Vertical Layout Group + Content Size Fitter)
- Container (Grid Layout Group)
- Slot
- Slot
- Container (Grid Layout Group)
- Slot
- Slot
ye sorry I had to go
can the container also have Text??
Yes
It will be aligned along with the containers
The text should be part of Container White . . .
My bad, read wrong
It will be aligned as the 8th image
Which should, honestly, be a vertical layout group itself . . .
Make Container White a vertical layout group with two children: text label and container for grid layout . . .
It's important to note that the 1st Layout Group may have a Content Size Fitter. In this case, its children should be driven by its Control Children Size.
If multiple Content Size Fitters are added, a warning can be thrown, but if you don't care, you can surely ignore it and it will still work
Are you referring to me?
Should I add TMP as a component to the container?
Yes
Container (Vertical Layout Group)
- Text
- Slot Container (Grid Layout Group)
- Slot
- Slot
I believe this would be the layout . . .
Group (Vertical Layout Group + Content Size Fitter)
- Container (Vertical Layout Group)
- Text Label
- Container (Grid Layout Group)
- Slot
- Slot
Well, that's the same as mine..
This isn't related at all to coding and should probably be moved to #💻┃unity-talk
Yeah, I didn't see your new version. That should work . . .
YES! IT WORKED
thanks you 2
@willow scroll teamwork makes the dream work . . .
spitting facts my bro
And I wanted to understand how to use OnCollisionEnter2D
I wanted to make the character only be able to jump again after touching the ground
What about it do you have questions about?
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html
im a beginner and i want to make my own (3D) project but idk what to do
something not to hard but not super simple
a challenge
Have you tried !learn already?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
pong but in 3d
yeah
3D chrome t-rex
This game already exists, by the way. So you can take it as an example and make your own
For example, you could add road rotation and make dinosaur run in different ways for visuals
so what if i sort of mix chrome trex and subway surfers?
No. The dinosaur runs normally, but you just rotate the screen around. The player still only needs to press 2 buttons: up and down.
This can also include changing the angle of the road, for the dinosaur to run diagonally, or change the direction, for the dinosaur to run from right to left part of the screen
how did you do that with exists
what's the problem with this super basic cycling system? arrays are what i'm worst at so go easy on me lmao
void CycleArray()
{
GameObject FirstSlot = Bullets[0];
GameObject SecondSlot = Bullets[1];
GameObject ThirdSlot = Bullets[2];
Bullets[0] = SecondSlot;
Bullets[1] = ThirdSlot;
Bullets[2] = FirstSlot;
}
Maybe tell us what's not working as expected
my bad. "IndexOutOfRangeException: Index was outside the bounds of the array."
which doesn't make much sense, because it shouldn't be
You probably don't have 3 elements
public GameObject[] Bullets = new GameObject[2];
That would be the default value prior to any changes made from the Unity Editor Inspector
this also runs on start
Bullets[0] = NormalBullet;
Check your inspector values for bullets
That creates an array of size 2. Not one with a max index of 2
You'd also want 3 for 3 elements
The value you give in there is how many things you want the array to hold
Show us the inspector
That changes the default value an object is created with. Since it's public, it's serialized by the inspector. You need to change it there
It will not update in the inspector if an object instance already exists
So right now the Bullets array has nothing in it at all
You'll need to actually add three elements to it
even though i set something in code?
The value you set in code is the default
the inspector takes priority
also, it's supposed to start out with only one thing in it. i suppose i could make fake nothing variables for it
That would be the default value before an instance has been modified
I would also suggest making your slots an array, too.
so the issue is that i need to have three things in the array at start?
how do you mean?
Arrays are fixed size. They never change the amount of slots after creation
You need to make sure your array has enough space to hold everything
it should, though. it needs to have three slots (0,1,2)
i don't see why it wouldn't?
Right, and your array has 0 slots.
So give it 3 slots
i've tried that, no beans
Show the updated inspector
Okay, and what error are you getting now? What line?
ah, i think that it's an issue with a different piece of code. i'm trying to print the contents of the array to make sure it's working correctly
void PrintArrayContents()
{
string[] bulletNames = new string[Bullets.Length];
for (int i = 0; i <= Bullets.Length; i++)
{
bulletNames[i] = Bullets[i] != null ? Bullets[i].name : "null";
}
Debug.Log("Bullets array: " + string.Join(", ", bulletNames));
nvm fixed it!
should be < not <=
perfect, thanks guys :)
string[] bulletNames = Bullets
.Select(b => b != null ? b.name : "null").ToArray();
string[] bulletNames = Bullets
.Select(b => !string.IsNullOrEmpty(b) ? b.name : "null").ToArray();
Lists, Dictionaries and Arrays are scary especially when it comes to multidimension. 
I was trying to develop an AR app, I am a beginner . Can we use smartphone camera through usb cable to test the application when I click play?
ToArray doesn't look too favorable over his regular implementation - gc.
I wonder which one is faster
But linq is more readable, as for me
Also, what does "gc" mean?
I would assume the loop to be more performant (if Linq actually necessitates pushing/popping the lambda to the stack for each element, anyway?)
garbage collector
Speed isn't a concern. Garbage Collector clean up isn't good though - especially in gene development.
Although tbf, he's already allocated some memory for bullet names prior to the loop either way that'll likely be collected.
Hi, is there a way to have something like a LayerMask that I can Serialize / see and edit in the editor, but with Tags? I can't seem to find a solution for that, and I don't really want to rely on strings
Could probably use some enums that would either map to strings or convert to strings etc without going the custom editor path - assuming you are wanting selection rather than potential user error misspellings/typos.
does anyone know why doesn't it tween "sometimes"? it prints both "ayy" and "Tweening"
void Start()
{
defaultCanvas.alpha = 0f;
flashlightCanvas.alpha = 0f;
StartCoroutine(nameof(showDefaultCanvas));
}
public void showFlashlightCanvas() {
StartCoroutine(nameof(showFlashlightEnumerator));
}
IEnumerator showFlashlightEnumerator() {
LeanTween.alphaCanvas(flashlightCanvas, 1f, 1f);
yield return new WaitForSeconds(5f);
LeanTween.alphaCanvas(flashlightCanvas, 0f, 1f);
}
IEnumerator showDefaultCanvas() {
print("ayy");
yield return new WaitForSeconds(2f);
LeanTween.alphaCanvas(defaultCanvas, 1f, 1f);
print("Tweening");
yield return new WaitForSeconds(10f);
LeanTween.alphaCanvas(defaultCanvas, 0f, 1f);
}
Nope, you have to make a custom solution for that. Someone did a long time ago . . .
Oh damn
maybe you can use a design pattern that doesnt require tags at all
Maybe If I use some time and creativity
https://hastebin.com/share/eceqejoxol.csharp
Im trying to make an upgrade system where i change the current weapon to a new one, but this for loop is somehow causing issues and i cant figure out why, it says line 19 is the issue.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Its infuriating because Im pretty sure if this for loop didnt give me an errors the code would run smoothly
Not related to your problem, but you can remove the 'nameof' and it will work as well.
for (int i = 0; i <= weapons.Length; i++)
zero indexing... There is no element at index weapons.Length
huh
Could you explain what you mean by that im still confused
ah, you need to change it to showDefaultCanvas()
Remove the = character
you don't have any elements in the array i think
well i print the array length and it shows 2
which is what i have
i have 2 current weapons in the array
oh, i'll check if it works, could solve the problem
An array with 6 elements has elements at indexes 0-5. There is no element at index 6. In short, an array or list will never have an element at an index equal to it's length - it always ends at Length - 1. So you should terminate your loop prior to your cursor reaching Length
i'm having an issue where the gameobject variable CurrentBullet won't correctly set to the first slot of index of Bullets, that being Bullets[0]. the code is below, and i'm getting the error NullReferenceException: Object reference not set to an instance of an object even though Bullets[0] is a prefab of a bullet
CurrentBullet = InventoryP1.Bullets[0];
youre right
thanks
code still doesnt work but its not the for loop at least
i just put a break in there and its sorted
nevermind its working now
thank you very much
Ideally you'd just remove the = from i <= weapons.Length
uhh, so it looks like it plays the tween when im in the console tab, but doesn't when im in project tab
okay ill do that too just in case
An nre (null reference exception) would occur when you'd attempt to access a member of some class (using the dot operator or also called member access operator) but the reference is to null. tldr inventory p1 was found to be null.
right, but it shouldn't be null. there's a gameobject on that spot of the array
something isn't working right
But the error is suggesting that it most definitely is null (inventory p1) and that you ought to figure out why.
this did nothing to help
if (InventoryP1.Bullets[0] != null)
{
CurrentBullet = InventoryP1.Bullets[0];
}
Dalph's saying that if that line is throwing an NRE, it implies that InventoryP1 is null
right right, i'm confused on why that is lol
It does not get to the point where it accesses the array
It isn't an issue with accessing the array element.
ah
i see
at the very start of the code, Bullets[0] has a gameobject attatched. so i'm not clear on why it's null
public GameObject[] Bullets = new GameObject[3];
public GameObject NormalBullet;
public GameObject BouncingBullet;
// Start is called before the first frame update
void Start()
{
Bullets[0] = NormalBullet;
Bullets[1] = BouncingBullet;
}
(null).DoSomething();//nre, we found null where we expected a reference to some instance```
Your InventoryP1 variable is itself null, it has nothing to do with the arrays yet
ah
The error does not imply that Bullets[0] is null
got it got it
clearly i'm referencing it incorrectly
hmmm why is that
i have zero idea
How are you initializing the InventoryP1 variable?
Im making replays for my game, how would I store a gameobject in the .dat file for the replay?
You'd look where you assigned inventory p1. Whether through the inspector or code
is that even possible? 😭
private InventoryP1 InventoryP1;
Where do you set it's value?
That would be the declaration
oh. i see what i did wrong now (i think)
You'd have to assign it an actual reference somewhere prior to using it.
right
i.. can't figure out how to do that for whatever reason
it should correlate to the array 'Bullets'
this is my first time really having to reference another script, hence running into trouble
Make it public and drag-drop the object with the inventory p1 component - if it's a Unity Component.
Still, inspector referencing is preferred over code referencing and yes, there is a need unless they're literally in the same class.
yep.. i see. thank you, friend. hopefully it works now
what do you mean store a gameobject
Sorry phrased poorly
Im able to record a replay with my player in it - when I play the replay I want to instantiate the player gameobject again
I mean like
If I record a replay of a match, with 4 players - each player has different cosmetics
how would I instantiate each player with their cosmetics?
the same way you spawn them pretty much
how do you get their cosmetics when you spawn them in-game
You'd want to store the cosmetics settings in the save file
Then spawn and initilize them just like you originally did
Why my lean tween only plays when im in console tab, the "ayy" and "Tweening" prints when im not in console as well as in other tabs
void Start()
{
defaultCanvas.alpha = 0f;
flashlightCanvas.alpha = 0f;
StartCoroutine(showDefaultCanvas());
}
public void showFlashlightCanvas() {
StartCoroutine(showFlashlightEnumerator());
}
IEnumerator showFlashlightEnumerator() {
LeanTween.alphaCanvas(flashlightCanvas, 1f, 1f);
yield return new WaitForSeconds(5f);
LeanTween.alphaCanvas(flashlightCanvas, 0f, 1f);
}
IEnumerator showDefaultCanvas() {
print("ayy");
yield return new WaitForSeconds(2f);
LeanTween.alphaCanvas(defaultCanvas, 1f, 1f);
print("Tweening");
yield return new WaitForSeconds(10f);
LeanTween.alphaCanvas(defaultCanvas, 0f, 1f);
}
Could I not just save the gameobject of the player itself?
gameobjects arent serializable
You can't really serialize a whole gameobject
Need to do some manual serialization/deserialization
Oh
on the bright side, you get to make your own file format
i have a complicated question, sorry y'all. each bullet in my game has the variable 'BulletDamage', which contains exactly what you would think. on collision with a player, i need to code it to find the gameobject that collided with it, and then find the value of the variable 'BulletDamage' on that object, and then subtract it by the player's total life. the main part that confuses me is how to reference that specific aspect of a bullet within the script for the player. sorry for the loaded question!
There's nothing inherently wrong with that code and I don't think that the behavior you're describing can really be attributed to any core coroutine functionality 👀
You might hit up the "LeanTween" support/community channels to see if they have any ideas
okay, thanks
Though, particularly strange is that you say the Debug.Log()s don't log anything while looking at the console? Maybe Unity is confused - you might restart the editor for funsies
You don't put the logic in the player script. It's the bullet that inflicts damage, not the player. Add a script to the bullet (prefab?) which detects collisions, retrieves on what it hit the script contains the health, and subtract
the collision gives you a collider component so you use GetComponent<BulletDamage> with that and, hey presto you have your variable
The bullet should check what it collides with, then pass its damage variable to the collided object (to damage it). Most likely through an interface or component . . .
"The type or namespace name 'BulletDamage' could not be found (are you missing a using directive or an assembly reference?)"
if only it was that easy
Ah, then what is the class that BulletDamage is on, sorry I thought that was the class
it's a float variable on the script of the bullet prefab
which script? what is the class name?
i might end up having to do this, but it's a lot of work so i'm gonna try other ways first
the script on the bulletprefab. wdym?
which script, scripts have class names
"public class NormalBullet : MonoBehaviour"
so use NormalBullet instead of BulletDamage in what I said
right, but it's not always going to be 'NormalBullet'. the issue is that different bullets have different scripts attatched to them
then you need to use inheritance
elaborate, please
ok
public class Bullet : MonoBehaviour { public float BulletDamage; }
public class NormalBullet : Bullet { }
public class OtherBullet : Bullet { }
...
Bullet bullet = GetComponent<Bullet>();
damage = bullet.BulletDamage;
i see.. but the script needs to be able to dynamically pull the BulletDamage variable from whatever bullet collides with it, if i end up having fifty different types of bullets that won't work
that is what the last 2 lines do
i honestly don't get it, i'll just try adding it into my code i suppose
what don't you understand?
the top three lines
those are classes
look at what you have now
public class NormalBullet : MonoBehaviour
NormalBullet inherits from Monobehaviour.
All I am doing is adding a step in the middle so that all bullets can be treated the same
so Bullet inherits Monobheavior, and NormalBullet inherits Bullet, and all other bullets inherit Bullet?
ah, so all of the other scripts by extension inherit MonoBehaviour as well?
yes
where should
public class Bullet : MonoBehaviour { public float BulletDamage; }
be placed?
in a new script
with just that?
with whatever you want but that is a start. no doubt you will find other stuff to put in it
so to summarize, the new script Bullet will have variable BulletDamage which all other scripts inherited under it can change to their own variable?
their own value, i mean
yes, exactly
and where should this be placed? empty gameobject?
no where, the other scripts that inherit it will go on the gameobjects
alright, i'll try to implement this. thank you, friend.
so in the code of a bullet, should i be editing Bullet.BulletDamage?
or wouldn't that change it for all others, so that's no good
no, you change the value in NormalBullet and OtherBullet or whatever bullets you have
so would
public float BulletDamage = 1;
``` be correct, for instance?
BulletDamage appears in those scripts just as if it was a locally declared variable
no, you do not need to declare it in the inheriting scripts because it already exists for you
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.VisualScripting;
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
private float hor;
private float speed = 8f;
private float jmpPower = 16f;
private bool isFacingRight = true;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
// Update is called once per frame
void Update()
{
hor = Input.GetAxisRaw("Horizontal");
if (Input.GetKeyDown("Jump") && IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jmpPower);
Console.WriteLine("Jump button pressed.");
}
if (Input.GetKeyUp("Jump") && rb.velocity.y > 0f)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
Console.WriteLine("Jump button released.");
}
Flip();
}
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}
void FixedUpdate()
{
rb.velocity = new Vector2(hor * speed, rb.velocity.y);
}
private void Flip()
{
if (isFacingRight && hor < 0f || !isFacingRight && hor > 0f)
{
isFacingRight = !isFacingRight;
Vector3 localScale = transform.localScale;
localScale.x *= -1f;
transform.localScale = localScale;
}
}
}
I have this code right here, and the movement works, but the jumping doesn't.
I tried to debug it with Console.WriteLine, but it isn't printing anything either.
Pretty sure Console.WriteLine doesn't work in Unity. Use Debug.Log instead
oh oops
not showing in the console either...
Hi i think when the enemy is hit it counts ALL hits while the weapon is in the enemy. How would I change this? Thanks
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.
Try logging IsGrounded() outside of any of the if statements
thats what i was doing atm LOL
Use OnTriggerEnter
Will try [instead of OnTriggerStay]?
im saving it btw. nothing is writing in the console.
If you put a log in Update outside of any if statments and nothing is printing, then there are no active objects in the scene with this script on it
@polar acorn nothing happens - no anim plays, and no hitparticles are instantiated
outside, it is printing
Ah, so wc.IsAttacking is probably not true when the collision starts. Unsure what sets that, but try keeping it in Stay and setting wc.IsAttacking to false after it hits once?
Or make a new boolean for beenAttacked, set it to true inside the if, and set it to false in OnTriggerExit
will try thanks
Okay so it is printing? What is it printing?
outside of the if statements it just prints whatever i want it to. inside the if statements it does nothing. it seems like Input.GetKeyDown(KeyCode.Space) && IsGrounded() and Input.GetKeyUp(KeyCode.Space) && rb.velocity.y > 0f aren't doing something. I'm gonna put an else statement and see if anything changes.
So did you log the value of IsGrounded
yes. nothing happens
i can't figure out how to implement these last two parts. i need to find the BulletDamage correlated to the object that collided with the player, and i can't seem to figure out how to do that
it's more streamlined but i still can't figure out how to actually obtain the variable
What do you mean "nothing happens"? Does it log something or not?
so what code do you have now in the Player collision
@polar acorn worked, tysm for the help :))
If you put a log in Update outside of any if statments and nothing is printing, then there are no active objects in the scene with this script on it
private void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag.Equals("Bullet"))
{
float damage = Bullet.
PlayerHit.Play();
life --;
Player1HP.SetText("Player1 HP = " + life + "!");
if(life == 0){
Player.SetActive(false);
PlayerDead.Play();
}
}
}
can't figure out how to subtract life by the correct BulletDamage
oh you're saying to put isGrounded at the outside of the if statement. i understand now
so you need the GetComponent i showed you on coll.gameObject
i see the problem now. it says false when it is supposed to be true.
yeah, i can't seem to format it right
that's the problem
Bullet bullet = coll.gameObject.GetComponent<Bullet>();
okay i found the issue. return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer); is returning False even though its true.
life -= coll.gameObject.GetComponent<Bullet>();??? i don't understand
you're naming a variable
did I write that ?
ah
ahhh. GroundCheck object has the wrong position
i see now. oops
someone please explain this to me:
if(Input.GetKeyDown(jumpButton))
{
rb.AddForce(new Vector3(0,jumpForce, 0), ForceMode.Impulse)
}
the context u need is that this is obviously a script to make the gameobject jump, rigidbody has been set to the variable rb, and jumpforce is 5
i know what it does but i dont know why it does this and i especially dont know why i have to use rigidbody physics calculations (hardly know what that means) instead of just transform.position += Vector3.up * Time.deltaTime
how could i check if a player is moving?
im thinking the script checks if the x or y axis is changed but i don't know how id code that
Check your rigibody's .velocity vector
im certainly not qualified but im pretty sure you can use rb.velocity.magnitude > 0f; or something to check if the velocity is higher than zero (thats probably wrong but i tried)
Each frame, store your position in a private Vector3 in your class. But before that, use Vector3.Distance to compare your last and current position. If the distance is greater than some threshold (could maybe be 0), you have moved
Ofc if you have a rigidbody then see the suggestions above
AddForce adds a force towards the direction you specify, resulting in a change in velocity
If you use transform to move a rigidbody object then it will not properly notify the physics system about it and you will run into oddities such as glitchy collisions
trying to draw a square. would this be a good way to calculate points?
public override List<fv2> GetPoints()
{
List<fv2> points = new();
fv2 topLeft;
topLeft.x = center.x - size.x / 2;
topLeft.y = center.y + size.y / 2;
points.Add(topLeft);
fv2 topRight;
topRight.x = center.x + size.x / 2;
topRight .y= center.y + size.y / 2;
points.Add(topRight);
fv2 bottomRight;
bottomRight.x = center.x + size.x / 2;
bottomRight.y = center.y - size.y / 2;
points.Add(bottomRight);
fv2 bottomLeft;
bottomLeft.x = center.x - size.x / 2;
bottomLeft.y = center.y - size.y / 2;
points.Add(bottomLeft);
return points;
}
Looks ok to me
Though I would find this more readable:cs fv2 topLeft = new fv2(center.x - size.x / 2, center.y + size.y / 2);
Functionally the same
looks better, yeah. thanks! I'm working on a custom collider system using SAT, and im working on making box, polygon and capsule colldiers manually
That sounds fun. Did something similiar for my prop placement system recently (box, sphere, capsule, polygon), although it only does depenetration, not full physics
(I didn't want to use Collider components for this as it would have been overkill, and I want to do most of it on the C# side, not bound to a scene)
why isn't it working?
private Vector3 lastPos;
// Update is called once per frame
void Update()
{
if(rb.transform.position != lastPos)
{
Debug.Log("Moving");
}
else
{
Debug.Log("Not moving");
}
Flip();
lastPos = rb.transform.position;
Debug.Log(lastPos);
}
lastPos is changing
you could just check if rb.velocity.magnitude > 0
So your "controller" is generally either physics-based, or not.
If you're not leveraging the physics engine to control movement, yeah, you'll totally just like transform.position += Vector3.up * Time.deltaTime and the object will move exactly as you tell it to, which might also include clipping directly into other objects until you set up the logic and components to prevent that, floating in place until you write code to apply gravity, etc.
In a physics-based approach, you can just apply forces (among other techniques) and the object will inherently act as is physically appropriate for it's environment. It will collide with other physical objects, fall with gravity, be affected by drag, knock other objects around based on relative velocities and masses, etc.
You're not obligated to use one or the other, it's a choice. Taking the physics route, you sacrifice some amount of fine-grained control in order to easily tap in to a consistent physics simulation.
Often times, these controllers end up using a bit of either approach in different circumstances. And you can achieve the benefits of one without relying on the other - it just takes some additional work to implement. So they're not entirely mutually exclusive, but I think it's best to treat them as such until you get a handle on them
now it says its moving everytime
Try a small threshold like 0.01
You are Fliping it all the time 🤔
its not an actual flip
it turns the character left or right
it turns out you can't use lean tween in ienumerator
i was trying for 2h to check why my tween wasn't working
That's super unfortunate 🙁
did this if someone has the same problem
LTDescr tweenToggle = LeanTween.alphaCanvas(defaultCanvas, 1f, 1f);
tweenToggle.delay = 2.5f;
tweenToggle.setOnComplete(() => {
LeanTween.alphaCanvas(defaultCanvas, 0f, 1f).delay = 5f;
});
its certainly a challenge 😅, my system before this used unity's floating point system, which wasnt good for what i wanted to do. i've since switched to a fixed point system, which is meant to ensure determinism. as such i cant use any of unity's physics stuff. i already wrote my own kinematic physics in my previous system anyway, so most of that shouldnt change too much.
my main thing im dreading is collision solving and stuff. its taken me ages to even serialise fixed point numbers
I admire your persistence. That path scares me 👀
so doing something like that is going to be even worse
i want to get online multiplayer working in my fighting game, and apparently being able to ensure determinism this way makes it a lot easier.
which is why im doing this 😅
how could i change the animation from 1 animation to another?
Since i got the script to check if im moving, i want to make it so it switches the animation from idle to run
and if not, it switches back to idle
animation parameters
You probably wanna check this out or something similiar:
https://learn.unity.com/course/introduction-to-3d-animation-systems
How would one access the player settings version through script, to, for example, show the version to the player in my settings menu?
Specifically this part:
https://learn.unity.com/tutorial/4-1-introduction-to-general-animation-scripting?uv=2019.4&courseId=5eba874aedbc2a00219550ff&projectId=5ebaa08eedbc2a00215c11c3#5f35d4ebedbc2a1922947bb9:~:text=4.Setting Animator Parameter values
But it doesn't hurt to check the previous steps too
That's fine
Hi. I have a problem: I want to move the UI element to the place where the mouse cursor is (transform.position = Input.MousePosition;). But I want to move the mouse cursor only within the Canvas. I saw that the limits of the coordinates of the object in canvas are y = -490, 530. I wrote it like this: transform.position = new (x, Mathf.Clamp(y, -490, 530)
P.s. float x = Input.mousePosition.x;
float y = Input.mousePosition.y
But during the game, the Y coordinates of the object go -10, -1300. How can I fix or make restrictions somehow on canvas?
Gizmos.color = Color.white;
for (int i = 0; i < colliderPoints.Count; i++)
{
if (i == colliderPoints.Count)
{
Gizmos.DrawLine(colliderPoints[i-1], colliderPoints[0]);
continue;
}
Gizmos.DrawLine(colliderPoints[i], colliderPoints[i+1]);
}
am i doing this right?
im getting out of range exceptions for the second gizmos.drawline
Well, if you're looping over every element in colliderPoints, what do you think is gonna happen when you try to get the next point of the last one?
yeah i forgot about that, i changed colliderPoints.count to colliderPoints.count - 1;
succesfully drawing points
woohoo!
that will techniqly not include the lastpoint. maybe do a if (colliderpoints.count >= colliderpoints.count +1) then break from the for loop
it seems to work fine for me
okay this acctually doesn't work and i don't know why, both logs are printing
private void Start() {
defaultCanvas.alpha = 0f;
flashlightCanvas.alpha = 0f;
LTDescr tweenToggle = LeanTween.alphaCanvas(defaultCanvas, 1f, 1f);
tweenToggle.delay = 2.5f;
Debug.Log("toggle on");
tweenToggle.setOnComplete(() => {
Debug.Log("toggle off");
LeanTween.alphaCanvas(defaultCanvas, 0f, 1f).delay = 5f;
});
}
Why does this not work whenever i hit jump? If i did this correctly i should be almost 55 length units up in the sky but yet im still on the ground everytime i press it
Hey, i have this playerprefs,
However, my build is not rendering on that resolution, it's rendering on the default on the default one, idk how
Have you checked if Movement.OnGround is true
would this work? ```
[SerializeField] private Animator animator;
animator.runtimeAnimatorController = Resources.Load("") as RuntimeAnimatorController;``` (replace the "" with the name or path?)
It isnt infact true
huh
public virtual List<fv2> GetPoints()
{
if (colliderPoints == null || colliderPoints.Count == 00) {
return null;
}
foreach (fv2 point in colliderPoints)
{
point += (fv2)transform.position;
}
return colliderPoints;
}
why wont it let me change the point in the foreach loop
ima check it out
What is fv2
its a struct
This would replace the whole controller for the animator. The controller holds all of the animation clips and transitions.
Are you sure you want that? Didn't you just want to change to a running animation?
yeah i did
this is what it looks like right now
anyone knows the answer
Then that's definitely not what you want. Look at some guides, I already linked you one
alr
Well, for one, why use this over the built in Vector2 class? For two, it's a struct, so modifying the copy you're holding in the point variable won't affect colliderPoints at all
So OnGround is not responsive and i have no clue why
i need to use a fixed point vector 2 class.
is it a raycast to detect the ground?
uhh kind of
it works like one
its a sphere that detects it
from a empty body
But now that u mention it
it should be a raycast
How do i make a raycast in unity?
This is what detects it
the checksphere
What is GroundCheck - is that a transform on a GO parented to your player?
sounds like it could be a problem with the root moving and animating
GroundCheck is a trasnform yes
and it follows the character around
Yeah but im not getting either a true or false
By way of being a child of the character, or a script updating it's position?
How's GroundMask configured in the inspector?
As we all are on occasion 😁
And the problem is that the character is not jumping?
You should paste it 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.
Yes, if u put the file here we need to download the file, and I don’t know you, but I don’t personally download every file I find
Uh i dont think u do
With the sites, we can see directly by opening the link
I suspect what's happening might be this sequence of events:
- "Jump" button hit. Y velocity set for jump. (No
Controller.Move()called thereafter this frame) - Next frame. The character hasn't moved vertically, so
if (Movement.OnGround == true && Movement.GravityVelocity.y > 0)checks out - set y velocity to -2f
So the jump velocity is immediately cancelled out the next frame
Ohhh how would i fix that?
No post the code properly
The code embed doesn't work well on mobile discord, and it also lacks line numbers. People often neglect to set the language for syntax highlighting correctly as well. So the Unity server asks that you use an external paste site
doesn't help for mobile users.. they won't get the file/embed without having to download the text file on their device
Not on mobile. It often lacks the correct syntax highlighting and no line numbers . . .
Cannot open that, with those two arrows, with my phone. Without downloading it ofc
Yep ill start using the websites
for groundchecks and jumps i do the following
MoveFunction(finalVector);
where finalVector is constructed prior using the inputs (and the grounded state)
its (input * speed) + jump + simulatedGravity
if I can jump i
reset the Y velocity of the vector and then set jump to my upwards value
and also i use 1 value for grounded simulatedGravity and a different value for my airbourne simulatedGravity..
The Move() function is always being called.. but it either has a value for jump or its 0 in my update function i slowly smooth jump back to 0..
Jump ->
- Reset Vertical Velocity to 0 (this stops residual forces from affecting the jump)
- Set Jump value (this gets factored in the movement vector)
- Change Gravity to something less than the gravity i use when grounded
but its highly dependent on what ur code looks like to begin with
Would it be okay to ask for a screenshot of the code? Im not really a visual thinker so i cant visualize it well
im firing up the project right now..
not sure it'll help to see the code 😄 my scripts a bit messy but i dont care to share
Dw i have my fair share of messy code ill get thru it (probably)
ill post a link to the Character Controller code.. and u can just ask any questions u have about it
you using a Character Controller?
Yep ill do that
w/ the Move() function
Yeah i do now
i didnt before
but the inputs were laggy for some reason so i changed it back
imo its the easiest component to start w/ as a beginner
since its got things like gravity, steps/stairs, groundchecks built in
i was originally translating code i already wrote from python to C#
{
foreach (var plateau in plateaus)
{
Color randomColor = GetRandomColor();
Gizmos.color = randomColor;
foreach (var position in plateau.GetCells())
{
Vector3 worldPosition = GridToWorldPosition(position);
float cubeSize = ChunkManager.Instance.scale * 0.9f;
Gizmos.DrawCube(worldPosition, Vector3.one * cubeSize);
}``` seems like `OnDrawGizmo()` keeps getting a new color every frame, very disco but how can i give a random color to every plateau?
In my original code i didnt even use groundchecks as it was in godot
no clue how i got it to work
Oh what is this? never seen anything like it
serialize fields... (allows private variables to get exposed in the inspector)
Oh that is very handy to know
I have to imagine there's a better way, but you could use a dictionary of plateau instances to colors... though, if plateau cells can change that might be a bit of a memory leak. I guess you could have plateaus roll their own colors as well - an editor-only property which rolls a value and sets the backing field if not set.
...or maybe you could hash instance IDs into a color? 😅
thanks for that
the Move() function and the JumpCheck() functions are the important parts
you can see i Just set the jump value
seems like a lot of trouble for just some random colors😅 think ill try setting up a counter and multiply it by the colorvalue or something
That does seem like a substantially better idea 👍
jump vector gets added to finalVector (if its zero thats fine too, its like it isnt even there).. and then below my Move() function.. im just lerping the jump value back to zero
I am very overwhelmed i was not expecting 274 lines of code wow
soo after i jump.. it eventually gets set back to zero (back to normal)
uh might take me some time to understand it
!code share urs
📃 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.
im sure its easier just to explain it in the context of your code
public void ResetVerticalVelocity()
{
jump.y = 0f;
gravitySim = 0f;
}``` heres the function i call everytime i go to jump
sets the y property of my jump vector back to zero and also temporarily sets my gravity forces to 0 (to allow a good jump)
private void ApplyGravity()
{
if (characterController.isGrounded && gravitySim < playerSettings.gravity)
gravitySim = playerSettings.gravity;
gravitySim += playerSettings.gravity * Time.deltaTime;
}``` and my gravity function sets the `gravitySim` variable i add into my vector to w/e it should be.. (if im grounded it checks and sets it to some small number -1 or -2)
if im not grounded (in the air) it keeps adding to it until im grounded again.. :
gravitySim += playerSettings.gravity * Time.deltaTime;
thanks 🙂
i named them in comments with a .CS at the end
Most variables arent yet in use
they are for use in the future
and can u explain briefly ur situation?
what happens when you jump
what do you want to happen in your jump
no worries.. i do that too.. (add in variables that i don't need yet)
it helps me plan better..
When i jump, nothing happens and when i jump i want to well just jump to start with
ill do some polishing
after it works
does this run?cs if (Movement.OnGround == true && Input.GetButtonDown("Jump")) { Movement.GravityVelocity.y = Mathf.Sqrt(Movement.JumpHeight * -2f * Movement.GravitySpeed); }
you can put a log in there to test
Give me a second and ill tell you
if (Movement.OnGround == true && Input.GetButtonDown("Jump"))
{
Debug.Log("We pressed jump and we're grounded so apply jump");
Movement.GravityVelocity.y = Mathf.Sqrt(Movement.JumpHeight * -2f * Movement.GravitySpeed);
}```
@raw token a bit less disco now👍
Gives me Timberborn vibes haha
Beautiful! Disco is dead 🥲
lol im actually attempting to mimic their fluid system. much simpler though
Also is there a way to make unity not use 100% of my GPU?
Ohh now i see it
Yeah their fluid system is pretty advanced
and ur player doesn't actually jump yet right?
assuming you are referring to your game: unless you limit the framerate, it is going to run as fast as it possibly can. this usually means that it's going to max out the CPU or GPU or both if it can
does anyone know hot to instantiate an object without it becoming a child of the object the script is on
use the Instantiate method, but one of the overloads that doesn't specify a parent or give it a different object as its parent if you want
using UnityEngine;
public class TestPlayer : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float jumpHeight = 3f;
public float gravity = -9.81f;
Vector3 velocity;
bool isGrounded;
void Update()
{
isGrounded = controller.isGrounded;
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (isGrounded && Input.GetButtonDown("Jump"))
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
basic of a system as u can get
how would i parent it to another object if i dont want it to instantiate on the object
apply downwards velocity (gravity)
if you want to give it a different parent, then pass the desired parent as the parent parameter for the Instantiate method. if you do not want to give it any parent, then don't use that overload
Wow i did now know the controller already had a isGrounded function
that is really helpful
Also i found the problem
just now
actually i combine the two Move() functions
b/c ive been told to avoid calling it multiple times
soo just adding in a gravityVector like my advanced controller i sent earlier is basically the difference
ignore all that 😄
thats my camera system..
- headbob
- breathing affect
- jump/fall knockback movement stuff
good to hear! 🙂
Yeah i can see that
i feel stupid cause the problem was a >
it was meant to be a <
now the height thingy works..
i just use forces and guesstimate.. i might implement a desiredHeight to my own jump 👍
yup, you'll have problems like that... usually you spend days hunting for a bug and its because you typed realVariable instead of RealVariable
or something just as silly 😄
Oh i "borrowed" some code from brackeys to solve that
and a bit more
for the jumping
how can i change the overload
look at the documentation for the Instantiate method
nothing wrong with that
Yep its the
´´´cs
//Movement.GravityVelocity.y = Mathf.Sqrt(Movement.JumpHeight * -2f * Movement.GravitySpeed);
´´´
line
damn i didnt do that correctly
!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.
meh i dont get it
//this is the code
the back tick is also the key usually above the Tab key
also the ~ squiggly if u use Shift + it
ahh im using a nordic keyboard
3 extra keys
whole keyboard out of order
yep thats the one
sooo many pretty keys! lol
Question regarding fixed update physics:
Say you were to implement an action that takes place in on frame such as a jump. You would check for input in Update().
But then, would you add the force for the jump in Update() as well, or should you set a variable to true when the input is detected, and add the jump in FixedUpdate() by checking for the variable?
the 2nd method..
The pronouncation is even better
you should poll for input in update.. you should act on those input in fixed
(physics) and all
Would I be correct in saying this makes the physics more consistent, but also less responsive if the fps is greater than the fixed update call?
if ur only running physics in FixedUpdate it should be consistent across all machines
can't say the same for input..
Thanks, I often see online tutorials do the first method, and that go me thinking about it
theres special things u can do.. like Rb.AddForce()
which.. even if u call them in Update... they won't be applied until the next fixed update
oh I didnt know that, is that also true for rb.velocity = ?
I see some tutorials also use that in Update()
depends on how its done..
you can use scaling.. like * time.deltaTime
if thats included. then it should be fine...
This image from an online tutorial for example
if they use just rb.velocity its possible that it could be applied more often than u want..
ya, thats fine because (getbuttondown).. is only gonna happen 1 frame
soo.. no matter how fast its running.. its gonna only get called once
until ur grounded again
you just gotta think about stuff like that a bit before u implement it..
heres an article i read once.. about input system + rigidbodies
im in the process myself of making all my projects work with the new input system
i believe it makes it easier to work w/ stuff (once u learn)
But if say, if you were to use the second method mentioned earlier where you set the variable to true, and you were running at, for example 360 fps. Would there be a few frames of difference between when the force is applied using the first and second methods?
at first it seems overly complicated.. but im still learning
does anyone know how I can do like when you press a button, it changes the camera?
yes
thers a chance ur input (bool gets flagged) maybe 10 - 20 frames before fixedupdate catches up
Cinemachine will make that quite trivial
How can i see the values in the inspector?
So adding the force in update directly is more responsive, but doing it in fixedupdate is deterministic?
use public variables..
or [SerializeField] private float myExposedFloat;
What do you mean by it changes the camera?
i usually control my rigidbodies by manually modifying their velocity
i use update usually (for more snappy movement)
but like u said.. its supposed to go in fixedupdate
I already use public variables on every single variable
Fair enough, I'm just unsure whether I prefer the first method for responsiveness, or the second for consistency/determinism
lets say that we have 2 cameras, a main one and a secondary one. I want the game when it notices that the player pressed a certain key, to change from the main camera, to the secondary one.
heres a good read/ starter content
cinemachine does that stuff for u automatically..
it uses (1) camera ur main one.. and sets its position to match ur Virtual Cameras (cinemachine cameras)
if u disable one of em.. its automatically gonna switch to the other.. (includes smoothing) -> transition
ok thanks
Learn to use Cinemachine in Unity for switching between cameras. We will code a system to automatically transition from one camera zone to another.
★ Join the Kingdom:
https://discord.gg/M2qfnUGxAz
★ Download Will & The Evil Duck for FREE (iOS & Android): https://gamedev.lu/games/will-and-the-evil-duck/
► The GameDev Website: https://gamedev....
basically u dont even need to do anything besides set one to Inactive..
does it matter if all variables that are preset are in a different script?
u can test in playmode.. (just disable one camera) you'll see it transition to the next one
you shouldn't set ur variable's protection level just to view them in the inspector...
if the variable needs to be accessed/modified from a script that its not itself in.. then you need public (to give access)
if it only needs accessed within the script its contained use private
Just one final question, if you were for example trying to repeat the exact same input in a scene, such as a frame perfect or a TAS, youd be locked in to having to use the second method?
private variables are better/ safer than public ones..
if u need to see a private variable in the inspector just add
[SerializeField] in front of it
Yeah but i need to see the public ones and atm i dont see anything
not sure tbh.. i use CharacterControllers for most of my stuff.. and my inputs are always in Update.. i don't have alot of experience doing stuff in fixedupdate..
but theres tons of games that rely on good input..
i'd look up Rythm games..
how do they do inputs
as input in a rhythm game are super important
Alright, tysm for the help
The public ones are meant to be like blueprints for every character later on when its multiplayer
goood luck mate 🍀
and so in the game settings before starting a save you can tweak the numbers u start with
i use a scriptable object for my players settings..
that way all my players settings are all in one place.. and i can swap them out.. depending on the player..
(say in the settings he inverts his mouse-look).. well i can have a ControllerSettings that has it marked for me..
playerSettings.invertedLook == true -> invert the look
ScriptableObjects may be useful for you...
you could also just use a normal class
public class MyPlayersSettings
Well atm i js have 2 scripts
no 3 mb
i forgot that i have the camera in a different script
actually now that i think about it
i could have everything in one script
you COULD but dont do it unnecessarily
unless it makes sense
On this article I’ll try to explain five design principles involved in object oriented programming that aim to have a more understandable…
theres a SOLID principals thing that we tend to use as structure
the first rule is Single Responsibility
It would make sense to have 2 scripts instead of 3
putting the Blueprint.cs in the movement.cs
makes sense
if it makes sense to you go for it..
just part of hte learning process..
if later on it doesn't make sense.. or doesn't work.. you'll know next time
Blueprints just contains all the variables the character needs to operate
But if i make a duplicate
it duplicates the settings
looks just like my ControllerSettings.cs
so it would make sense to put it in the movement code right?
So it should be seperate?
see
i thought the opposite..
at First i had all these variables inside the Controller script..
and then it started getting really big.. so i saved them elsewhere..
and just use a reference to them
for example here instead of my jumpSmoothing being part of the script.. its part of the ControllerSettings.. (if i change out the reference the code will still all work)
just new values instead
Yeah it works the same in mine except im using it more so i can fine tune the values
and thats every single value
almost
i can't say for sure whats better for your project..
i can just give suggestions.. and examples of mine for u to look at..
in the end its up to you whats better for you
Idk ill see later down the line for now i js gotta know why my jumping works 30% of the time
like i have to press space twice
and then the third time it jumps
i think its trying to work against ur gravity..
once it finally cancels out ur gravity it'll jump
Sounds like you're making a classic mistake like reading input in FixedUpdate
may need to reset ur Y velocity to 0 right before the jump
if -> Jump
Yvelocity = 0;
// then do ur jump
Yeah my dormant gravity on the ground is -2
to test.. make it a really low value.. or zero
Did you ever share your full script?
and then try to jump..
if u can jump w/ a value of 0.. then its probably the gravity..
if u still cant jump.. its not
but he's since modified it
using UnityEngine;
public class TestPlayer : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float jumpHeight = 3f;
public float gravity = -9.81f;
Vector3 velocity;
bool isGrounded;
void Update()
{
isGrounded = controller.isGrounded;
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
if (isGrounded && Input.GetButtonDown("Jump"))
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
// Combine horizontal and vertical movement
controller.Move((move * speed + velocity) * Time.deltaTime);
}
}
``` heres a snippet i sent him earlier for his gravity/jump
that version works fine in my project.. but i haven't tested thoroughly
its snack time
it is not
alrighty.. set it back to what u had before.. and go a different troubleshooting direction
It works, but only 30% of the time
put a debug back in the jump method and see if its debuggin only 30% of the time
i mean im getting the Debug.Log("Works!"); back but no jumping
oh okay... soo thats a good sign so far
the method gets called.. but it only acts 30% of the time
can u share ur new version?
just for others to jump in and help
Wait nvm im not getting it i saw it wrong

Sure
i gotta go get lunch for work.. good luck 👍
No worries
jump only working 30% of the time - user reports
the cat ninja deleted? 😄
Cat on keyboard is the best thing ever
Oh you're using CharacterController.isGrounded which is notoriously awful. Use a real grounded check
that js made me laugh
She wants dinner way too early and is being a pest
🫣 i still gotta do this too
im heavily reliant on it just working
Also you're doing multiple Move calls per frame which is a known issue
mentioned that earlier
Alreaddy did and it didnt work