#💻┃code-beginner

1 messages · Page 425 of 1

tiny rain
#

Just look near that message

slender nymph
#

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

teal viper
tiny rain
#

I said weakness as they do their job normally, but not for this

slender nymph
#

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

tiny rain
#

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

slender nymph
#

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"

tiny rain
#

Just how many arguments are you gonna try against me after so many that I can counter?

tiny rain
#

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.

eternal needle
# tiny rain Just how many arguments are you gonna try against me after so many that I can co...

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.

tiny rain
# eternal needle your counter argument is essentially not actually understanding what anyone wrot...

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

eternal needle
#

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

slender nymph
#

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.

tiny rain
#

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

eternal needle
#

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"

tiny rain
#

I'm out, bye

tiny rain
#

There's that feature.

#

I'm out fr

languid spire
tiny rain
eternal needle
tiny rain
#

Shift x by int byte count, perform & with y

languid spire
tiny rain
#

Can you deny that you're just picking on me using whatever you can find?

#

Stop pinging me for today, seriously.

languid spire
#

I'll do better than that, I'll block you

amber nimbus
#
    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 :/
slender nymph
#

you should log what the color being assigned actually is

amber nimbus
#

Oh yeah, good idea

slender nymph
#

instead of your mostly useless "change color" log, do this: Debug.Log($"Color changed to {color} on {name} ({GetInstanceID()})");

amber nimbus
#

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

ivory bobcat
#

Are you looking at the correct clone? Which clone is the one not changing?

amber nimbus
#

All of them

#

They should all be red

#

but they are white

slender nymph
#

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

eternal needle
#

When are you calling set color?

#

If its before start runs, you're overwriting the value in start

ivory bobcat
#

Place a comma and this after the string message with debug:cs Debug.Log($"...", this);

amber nimbus
slender nymph
#

yep, that'll be before Start

ivory bobcat
amber nimbus
slender nymph
#

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

amber nimbus
eternal needle
amber nimbus
#

Aight thanks :D

sharp abyss
#

but when I press w after that

#

its like this

#

so I cant move forward

#

limits are like this

verbal dome
#

A video could help

sharp abyss
ionic zephyr
#

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??

verbal dome
ionic zephyr
verbal dome
#

Use mp4 please so it embeds into discord

sharp abyss
#

oohh didnt see that

#

bruv why does mkv even exist for

strong wren
verbal dome
#

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

sharp abyss
verbal dome
#

It has settings for friction and bounciness

ionic zephyr
# ionic zephyr like this

I think the probken is that the size of the group doesnt depende of the slot number but still, I need help

verbal dome
#

Make sure that the feet have different physics materials so you don't edit both at once

sharp abyss
#

I forgot I could assign physics materials not only to ground but to the limbs

verbal dome
#

Looks like the friction hack would solve this

sharp abyss
#

should I make its friction always 0 or on a condition in the script?

verbal dome
#

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

sharp abyss
#

okay thanks

verbal dome
#

So yeah you have to script it

ionic zephyr
cinder crag
#

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

pliant sleet
#

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)

slender nymph
slender nymph
pliant sleet
#

so should I use tags ?

slender nymph
#

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

cinder crag
slender nymph
#

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

cinder crag
#

im a bit confused on which one i gotta check

pliant sleet
slender nymph
#

and consider going through some beginner unity courses if this is all too unfamiliar for you

ionic zephyr
#

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??

ionic zephyr
#

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

cosmic dagger
ionic zephyr
#

that contains a text and a grid

#

sorry, I might have said it wrong

cosmic dagger
ionic zephyr
ionic zephyr
outer coral
#

Are SOs terrible to modify? Like should I not be modifying the information on an SO and they should be strictly storing?

slender nymph
#

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

ionic zephyr
outer coral
#

Thanks boxfriend thats helpful

cosmic dagger
# outer coral Are SOs terrible to modify? Like should I not be modifying the information on an...

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 . . .

ionic zephyr
outer coral
cosmic dagger
ionic zephyr
#

yes I do

cosmic dagger
# ionic zephyr 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 . . .

ionic zephyr
#

I duplicated slots and it doesnt separate

cosmic dagger
rigid ridge
#

how do i get the start function back on my script

cosmic dagger
# ionic zephyr

Wait, so is the overlayed — 4th — row supposed to be under the top or bottom Resources group?

verbal dome
cosmic dagger
rigid ridge
ionic zephyr
wintry quarry
verbal dome
#

Or ask ChatGPT to make an empty Start function for you 🧌

cosmic dagger
# rigid ridge oh okay

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!

ionic zephyr
cosmic dagger
#

What is the hierarchy or layout? Does the VLG consists of the 3 horizontal slots?

halcyon dagger
#

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)]
halcyon dagger
#

Alr thx

verbal dome
#

Are you gonna move the question there because I have some answer/clues for you

ionic zephyr
ionic zephyr
ionic zephyr
safe radish
#
    {
        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
willow scroll
ionic zephyr
# ionic zephyr this is what I get when it expands

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??

safe radish
#

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

willow scroll
safe radish
#

but shouldnt List<Vector3Int> newlyAddedPositions = new List<Vector3Int>(); clear the old list?

willow scroll
willow scroll
verbal dome
ionic zephyr
verbal dome
#

Well yeah, technically doesn't clear it but creates a new one

ionic zephyr
willow scroll
ionic zephyr
#

this is what I get when it expands

safe radish
#

so instead of clearing the lists and refilling them i keep generating new ones?

ionic zephyr
ionic zephyr
willow scroll
# ionic zephyr

This is the same you have previously shown as your objective

#

You just have 2 slot containers

willow scroll
willow scroll
# ionic zephyr

If you want several slot containers to consider each other's height, put them inside of the same parent

willow scroll
ionic zephyr
#

the I add the slots:

#

this is the process

willow scroll
ionic zephyr
#

what top?

#

on top of GloveInventory

willow scroll
#

Actually, top stretch, in your case

teal viper
willow scroll
#

In the 1st variant, the already existing variable is being used

teal viper
#

Both one and two create new lists.

#

You're just using an implicit constructor in the first one.

#

In both.

ionic zephyr
willow scroll
teal viper
#

First one assigns a new list to an existing variable.

willow scroll
teal viper
#

If you wanted to reuse a list, you can clear it and keep on using it. list.Clear()

safe radish
#

right now i made the list a class variable and just calling clear() at the start of every iteration

#

that seems to work fine

teal viper
willow scroll
#

These are different

#

It creates a new value

#

That's the same as

myOldList = new() { 1, 2, 3 };
teal viper
#

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.

willow scroll
ionic zephyr
queen adder
#

No dlich is right

willow scroll
queen adder
#

It's a different memory address essentially

teal viper
willow scroll
#

That's why myOldList, and not myOldList2 is used

queen adder
#

There two separate objects but can have the same values

willow scroll
teal viper
queen adder
#

What are you trying to accomplish feel like we're getting off topic

willow scroll
ionic zephyr
queen adder
#

Oh what lmao

teal viper
cosmic dagger
# ionic zephyr

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)?

willow scroll
willow scroll
willow scroll
ionic zephyr
ionic zephyr
teal viper
ionic zephyr
verbal dome
#

It's pretty basic C# stuff tbh.

willow scroll
#

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

cosmic dagger
# ionic zephyr YES

Okay, I did not know the VLG group was a group of slots with the label. Now I understand . . .

ivory bobcat
# safe radish so instead of clearing the lists and refilling them i keep generating new ones?

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.

teal viper
ionic zephyr
queen adder
#

You guys are saying the same thing pretty much lol?

safe radish
teal viper
willow scroll
queen adder
#

When you call new on a existing variable the old one is Def getting gcd

teal viper
willow scroll
cosmic dagger
ionic zephyr
willow scroll
teal viper
queen adder
#

Yeah you did sashok

#

But you know the old instance gets gcd right?

ionic zephyr
willow scroll
queen adder
#

If you mean the memory address then yes it is lol

#

That's the whole point of new()

willow scroll
#

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

teal viper
willow scroll
teal viper
ivory bobcat
#

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.

willow scroll
queen adder
#

No lmao you guys were arguing different things

teal viper
#

Not me. I've been saying that a new instance is created in both cases.

queen adder
#

But that's why I said your both right?

teal viper
#

Right. I guess I misunderstood what they meant. Off to bed.

willow scroll
#

I'm saying that:

    1. Reusing an already existing variable does not create a new variable
myOldVariable = new();
    1. new() does create a new object of type, regardless of it being reference or value. But it does not create a new variable
cosmic dagger
#

If I'm right, and he's right . . . then you're right, right?

cosmic dagger
ionic zephyr
cosmic dagger
# ionic zephyr

What about your grid layout? The container for that should have a content size fitter . . .

ionic zephyr
willow scroll
#

@ionic zephyr

#
Group (Vertical Layout Group + Content Size Fitter)

  - Container (Grid Layout Group)
    - Slot
    - Slot

  - Container (Grid Layout Group)
    - Slot
    - Slot
ionic zephyr
willow scroll
#

It will be aligned along with the containers

cosmic dagger
#

The text should be part of Container White . . .

willow scroll
#

It will be aligned as the 8th image

cosmic dagger
#

Which should, honestly, be a vertical layout group itself . . .

willow scroll
#

A text?

#

This depends on the desired position

cosmic dagger
#

Make Container White a vertical layout group with two children: text label and container for grid layout . . .

willow scroll
#

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

ionic zephyr
willow scroll
#
Container (Vertical Layout Group)

  - Text

  - Slot Container (Grid Layout Group)
    - Slot
    - Slot
cosmic dagger
#

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
willow scroll
ivory bobcat
cosmic dagger
ionic zephyr
#

thanks you 2

cosmic dagger
stiff edge
#

Hi

#

I'm VERY new at programming

ionic zephyr
stiff edge
#

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

polar acorn
obsidian shoal
#

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

willow scroll
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

polar acorn
obsidian shoal
willow scroll
#

3D chrome t-rex

obsidian shoal
#

ohhhh

#

good idea

#

thank you

willow scroll
#

For example, you could add road rotation and make dinosaur run in different ways for visuals

obsidian shoal
#

so what if i sort of mix chrome trex and subway surfers?

willow scroll
#

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

obsidian shoal
wanton kraken
#

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;
    }
ivory bobcat
wanton kraken
#

my bad. "IndexOutOfRangeException: Index was outside the bounds of the array."

#

which doesn't make much sense, because it shouldn't be

ivory bobcat
#

You probably don't have 3 elements

wanton kraken
#
    public GameObject[] Bullets = new GameObject[2];
ivory bobcat
#

That would be the default value prior to any changes made from the Unity Editor Inspector

wanton kraken
#

this also runs on start

Bullets[0] = NormalBullet;
ivory bobcat
#

Check your inspector values for bullets

polar acorn
wanton kraken
#

ahhh, i didnt realize that counts index 0

#

it should be 0,1,2

ivory bobcat
polar acorn
#

The value you give in there is how many things you want the array to hold

wanton kraken
#

i'm still getting the error, though

#

even after changing it to [3]

ivory bobcat
#

Show us the inspector

polar acorn
#

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

wanton kraken
ivory bobcat
#

It will not update in the inspector if an object instance already exists

wanton kraken
#

a bit new to all of this

#

i see

polar acorn
#

You'll need to actually add three elements to it

wanton kraken
#

even though i set something in code?

polar acorn
#

the inspector takes priority

wanton kraken
#

also, it's supposed to start out with only one thing in it. i suppose i could make fake nothing variables for it

ivory bobcat
#

That would be the default value before an instance has been modified

eager elm
wanton kraken
#

so the issue is that i need to have three things in the array at start?

wanton kraken
polar acorn
#

You need to make sure your array has enough space to hold everything

wanton kraken
#

it should, though. it needs to have three slots (0,1,2)

#

i don't see why it wouldn't?

polar acorn
#

So give it 3 slots

wanton kraken
#

i've tried that, no beans

polar acorn
wanton kraken
polar acorn
#

Okay, and what error are you getting now? What line?

wanton kraken
#

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 :)

willow scroll
tawdry rock
#

Lists, Dictionaries and Arrays are scary especially when it comes to multidimension. UnityChanOops

steel dew
#

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?

ivory bobcat
willow scroll
#

But linq is more readable, as for me
Also, what does "gc" mean?

raw token
#

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

ivory bobcat
#

Although tbf, he's already allocated some memory for bullet names prior to the loop either way that'll likely be collected.

desert plinth
#

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

ivory bobcat
summer shard
#

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);
    }
cosmic dagger
cosmic quail
desert plinth
celest holly
#

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.

#

Its infuriating because Im pretty sure if this for loop didnt give me an errors the code would run smoothly

eager elm
raw token
celest holly
eager elm
ivory bobcat
#

Remove the = character

summer shard
celest holly
#

well i print the array length and it shows 2

#

which is what i have

#

i have 2 current weapons in the array

summer shard
raw token
wanton kraken
#

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];
celest holly
#

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

raw token
summer shard
celest holly
ivory bobcat
wanton kraken
#

right, but it shouldn't be null. there's a gameobject on that spot of the array

#

something isn't working right

ivory bobcat
wanton kraken
#

this did nothing to help

        if (InventoryP1.Bullets[0] != null)
        {
            CurrentBullet = InventoryP1.Bullets[0];
        }
raw token
wanton kraken
#

right right, i'm confused on why that is lol

short hazel
#

It does not get to the point where it accesses the array

ivory bobcat
wanton kraken
#

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;
    }
ivory bobcat
#
(null).DoSomething();//nre, we found null where we expected a reference to some instance```
short hazel
#

Your InventoryP1 variable is itself null, it has nothing to do with the arrays yet

wanton kraken
#

ah

raw token
wanton kraken
#

got it got it

#

clearly i'm referencing it incorrectly

#

hmmm why is that

#

i have zero idea

raw token
#

How are you initializing the InventoryP1 variable?

trail gull
#

Im making replays for my game, how would I store a gameobject in the .dat file for the replay?

ivory bobcat
#

You'd look where you assigned inventory p1. Whether through the inspector or code

wanton kraken
raw token
ivory bobcat
wanton kraken
#

oh. i see what i did wrong now (i think)

ivory bobcat
#

You'd have to assign it an actual reference somewhere prior to using it.

wanton kraken
#

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

ivory bobcat
#

Make it public and drag-drop the object with the inventory p1 component - if it's a Unity Component.

wanton kraken
#

they're on the same gameobject

#

no need

#

nvm

#

i did it

ivory bobcat
#

Still, inspector referencing is preferred over code referencing and yes, there is a need unless they're literally in the same class.

wanton kraken
#

yep.. i see. thank you, friend. hopefully it works now

sand heath
trail gull
#

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

sand heath
#

Instantiate(GameObject)

#

Is your question how to get the 'GameObject' to instantiate?

trail gull
#

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?

sand heath
#

the same way you spawn them pretty much

#

how do you get their cosmetics when you spawn them in-game

verbal dome
#

You'd want to store the cosmetics settings in the save file

#

Then spawn and initilize them just like you originally did

summer shard
#

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);
    }
trail gull
sand heath
#

gameobjects arent serializable

verbal dome
#

You can't really serialize a whole gameobject

#

Need to do some manual serialization/deserialization

trail gull
#

Oh

sand heath
#

on the bright side, you get to make your own file format

wanton kraken
#

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!

raw token
raw token
# summer shard 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

short hazel
languid spire
cosmic dagger
wanton kraken
#

if only it was that easy

languid spire
wanton kraken
#

it's a float variable on the script of the bullet prefab

languid spire
#

which script? what is the class name?

wanton kraken
wanton kraken
languid spire
#

which script, scripts have class names

wanton kraken
#

"public class NormalBullet : MonoBehaviour"

languid spire
#

so use NormalBullet instead of BulletDamage in what I said

wanton kraken
#

right, but it's not always going to be 'NormalBullet'. the issue is that different bullets have different scripts attatched to them

languid spire
#

then you need to use inheritance

wanton kraken
#

elaborate, please

languid spire
#

ok

public class Bullet : MonoBehaviour { public float BulletDamage; }
public class NormalBullet : Bullet { }
public class OtherBullet : Bullet { }
...
Bullet bullet = GetComponent<Bullet>();
damage = bullet.BulletDamage;
wanton kraken
#

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

languid spire
#

that is what the last 2 lines do

wanton kraken
#

i honestly don't get it, i'll just try adding it into my code i suppose

languid spire
#

what don't you understand?

wanton kraken
#

the top three lines

cosmic quail
languid spire
#

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

wanton kraken
#

so Bullet inherits Monobheavior, and NormalBullet inherits Bullet, and all other bullets inherit Bullet?

languid spire
#

yes

#

so they all have a BulletDamage variable which is easy to access

wanton kraken
#

ah, so all of the other scripts by extension inherit MonoBehaviour as well?

languid spire
#

yes

wanton kraken
#

where should

public class Bullet : MonoBehaviour { public float BulletDamage; }

be placed?

languid spire
#

in a new script

wanton kraken
#

with just that?

languid spire
#

with whatever you want but that is a start. no doubt you will find other stuff to put in it

wanton kraken
#

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

languid spire
#

yes, exactly

wanton kraken
languid spire
#

no where, the other scripts that inherit it will go on the gameobjects

wanton kraken
#

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

languid spire
#

no, you change the value in NormalBullet and OtherBullet or whatever bullets you have

wanton kraken
#

so would

    public float BulletDamage = 1;
``` be correct, for instance?
languid spire
#

BulletDamage appears in those scripts just as if it was a locally declared variable

languid spire
wanton kraken
#

oh right

#

ohhh

#

okay okay i think i understand

iron olive
#

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.

polar acorn
#

Pretty sure Console.WriteLine doesn't work in Unity. Use Debug.Log instead

iron olive
#

not showing in the console either...

lethal swallow
polar acorn
iron olive
#

thats what i was doing atm LOL

lethal swallow
iron olive
#

im saving it btw. nothing is writing in the console.

polar acorn
lethal swallow
#

@polar acorn nothing happens - no anim plays, and no hitparticles are instantiated

polar acorn
#

Or make a new boolean for beenAttacked, set it to true inside the if, and set it to false in OnTriggerExit

polar acorn
iron olive
# polar acorn 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.

polar acorn
iron olive
wanton kraken
#

it's more streamlined but i still can't figure out how to actually obtain the variable

polar acorn
languid spire
lethal swallow
#

@polar acorn worked, tysm for the help :))

polar acorn
# iron olive no

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

wanton kraken
#

can't figure out how to subtract life by the correct BulletDamage

iron olive
#

oh you're saying to put isGrounded at the outside of the if statement. i understand now

languid spire
iron olive
#

i see the problem now. it says false when it is supposed to be true.

wanton kraken
#

that's the problem

languid spire
iron olive
#

okay i found the issue. return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer); is returning False even though its true.

wanton kraken
#

you're naming a variable

wanton kraken
#

ah

iron olive
#

ahhh. GroundCheck object has the wrong position

wanton kraken
#

i see now. oops

ashen sonnet
#

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

iron olive
#

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

raw token
ashen sonnet
verbal dome
#

Ofc if you have a rigidbody then see the suggestions above

verbal dome
stuck palm
#

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;
    }
verbal dome
#

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

stuck palm
verbal dome
#

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)

iron olive
# iron olive how could i check if a player is moving?

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

summer shard
raw token
# ashen sonnet someone please explain this to me: ```c# if(Input.GetKeyDown(jumpButton)...

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

iron olive
verbal dome
#

Try a small threshold like 0.01

verbal dome
iron olive
#

ooooooooh that works

#

tysm

iron olive
#

it turns the character left or right

summer shard
#

it turns out you can't use lean tween in ienumerator

#

i was trying for 2h to check why my tween wasn't working

raw token
#

That's super unfortunate 🙁

summer shard
#

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;
});
stuck palm
#

my main thing im dreading is collision solving and stuff. its taken me ages to even serialise fixed point numbers

raw token
#

I admire your persistence. That path scares me 👀

stuck palm
#

so doing something like that is going to be even worse

stuck palm
#

which is why im doing this 😅

iron olive
#

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

summer shard
#

animation parameters

iron olive
#

its 2d

#

2d game

outer wigeon
#

How would one access the player settings version through script, to, for example, show the version to the player in my settings menu?

verbal dome
split dragon
#

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?

stuck palm
#
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

polar acorn
stuck palm
#

succesfully drawing points

rocky canyon
tawdry rock
summer shard
#

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;
    });
}
zenith crown
#

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

half notch
#

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

polar acorn
iron olive
# verbal dome That's fine

would this work? ```

[SerializeField] private Animator animator;
animator.runtimeAnimatorController = Resources.Load("") as RuntimeAnimatorController;``` (replace the "" with the name or path?)

zenith crown
#

huh

stuck palm
#
 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

zenith crown
#

ima check it out

stuck palm
verbal dome
stuck palm
iron olive
#

this is what it looks like right now

verbal dome
iron olive
#

alr

polar acorn
# stuck palm

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

zenith crown
stuck palm
pastel dome
zenith crown
#

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?

zenith crown
#

This is what detects it

#

the checksphere

raw token
#

What is GroundCheck - is that a transform on a GO parented to your player?

pastel dome
#

sounds like it could be a problem with the root moving and animating

zenith crown
#

and it follows the character around

zenith crown
raw token
zenith crown
#

child of the character

raw token
#

How's GroundMask configured in the inspector?

zenith crown
#

Like this where terrain is on the same layer as the GroundMask

raw token
#

Ah

zenith crown
#

wow i missed a =

#

im blind

raw token
#

As we all are on occasion 😁

zenith crown
#

Well fixed that

#

but that didnt fix it

#

so now im scratching my head harder

raw token
#

And the problem is that the character is not jumping?

zenith crown
#

Yes

#

Heres the code

timber comet
#

You should paste it here: !code

eternal falconBOT
zenith crown
#

Oh is it different?

#

I just pasted the code file directly

timber comet
timber comet
zenith crown
#

u just press the 2 arrow thingy

#

this thing

raw token
#

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, soif (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

zenith crown
#

Ohhh how would i fix that?

polar acorn
raw token
# zenith crown Uh i dont think u do

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

zenith crown
#

Oh makes sense

#

ill do it next time

#

thanks for telling me

rocky canyon
cosmic dagger
timber comet
# zenith crown

Cannot open that, with those two arrows, with my phone. Without downloading it ofc

zenith crown
#

Yep ill start using the websites

rocky canyon
#

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

zenith crown
rocky canyon
#

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

zenith crown
rocky canyon
#

you using a Character Controller?

rocky canyon
#

w/ the Move() function

zenith crown
#

i didnt before

#

but the inputs were laggy for some reason so i changed it back

rocky canyon
#

imo its the easiest component to start w/ as a beginner

#

since its got things like gravity, steps/stairs, groundchecks built in

zenith crown
#

i was originally translating code i already wrote from python to C#

safe radish
#
    {

        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?
zenith crown
#

no clue how i got it to work

zenith crown
#

Oh what is this? never seen anything like it

rocky canyon
#

serialize fields... (allows private variables to get exposed in the inspector)

zenith crown
#

Oh that is very handy to know

raw token
# safe radish ``` private void OnDrawGizmos() { foreach (var plateau in plateaus)...

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? 😅

zenith crown
#

thanks for that

rocky canyon
#

the Move() function and the JumpCheck() functions are the important parts

#

you can see i Just set the jump value

safe radish
rocky canyon
raw token
rocky canyon
#

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

zenith crown
#

I am very overwhelmed i was not expecting 274 lines of code wow

rocky canyon
#

soo after i jump.. it eventually gets set back to zero (back to normal)

zenith crown
#

uh might take me some time to understand it

eternal falconBOT
rocky canyon
#

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;

zenith crown
#

This is both the files

#

in one

rocky canyon
#

thanks 🙂

zenith crown
#

i named them in comments with a .CS at the end

#

Most variables arent yet in use

#

they are for use in the future

rocky canyon
rocky canyon
zenith crown
#

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

rocky canyon
#

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

zenith crown
#

Give me a second and ill tell you

rocky canyon
#
       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);
        }```
zenith crown
#

Yes it works

safe radish
#

@raw token a bit less disco now👍

zenith crown
raw token
safe radish
zenith crown
#

Also is there a way to make unity not use 100% of my GPU?

zenith crown
#

Yeah their fluid system is pretty advanced

rocky canyon
zenith crown
#

Nope

#

no y movement

#

at all

slender nymph
zenith crown
#

Ahh

#

how do i limit my FPS

#

to lets say 100 FPS

toxic pine
#

does anyone know hot to instantiate an object without it becoming a child of the object the script is on

slender nymph
#

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

rocky canyon
# zenith crown no y movement
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

toxic pine
rocky canyon
#

apply downwards velocity (gravity)

slender nymph
zenith crown
#

that is really helpful

#

Also i found the problem

#

just now

rocky canyon
#

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

zenith crown
#

Seeing this made me confused

#

then i saw everything on the right

rocky canyon
#

thats my camera system..

  • headbob
  • breathing affect
  • jump/fall knockback movement stuff
rocky canyon
zenith crown
#

Yeah i can see that

zenith crown
#

it was meant to be a <

rocky canyon
#

now the height thingy works..

#

i just use forces and guesstimate.. i might implement a desiredHeight to my own jump 👍

rocky canyon
#

or something just as silly 😄

zenith crown
#

and a bit more

#

for the jumping

slender nymph
#

look at the documentation for the Instantiate method

rocky canyon
zenith crown
#

damn i didnt do that correctly

#

!code

eternal falconBOT
rocky canyon
#

put a linebreak after the cs

zenith crown
#

meh i dont get it

rocky canyon
#
//this is the code
rocky canyon
#

the back tick is also the key usually above the Tab key

#

also the ~ squiggly if u use Shift + it

zenith crown
#

3 extra keys

#

whole keyboard out of order

rocky canyon
#

this one then i believe

zenith crown
#

yep thats the one

rocky canyon
nova swift
#

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?

rocky canyon
#

the 2nd method..

zenith crown
rocky canyon
#

you should poll for input in update.. you should act on those input in fixed

#

(physics) and all

nova swift
rocky canyon
#

jumpWhenReady = true

#
if(jumpWhenReady)
{
   //jump
   jumpWhenReady = false;
}```
rocky canyon
#

can't say the same for input..

nova swift
rocky canyon
nova swift
#

oh I didnt know that, is that also true for rb.velocity = ?

#

I see some tutorials also use that in Update()

rocky canyon
#

you can use scaling.. like * time.deltaTime

#

if thats included. then it should be fine...

nova swift
#

This image from an online tutorial for example

rocky canyon
#

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)

nova swift
#

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?

rocky canyon
#

at first it seems overly complicated.. but im still learning

mossy willow
#

does anyone know how I can do like when you press a button, it changes the camera?

rocky canyon
#

thers a chance ur input (bool gets flagged) maybe 10 - 20 frames before fixedupdate catches up

summer stump
zenith crown
#

How can i see the values in the inspector?

nova swift
rocky canyon
nova swift
rocky canyon
#

i use update usually (for more snappy movement)

#

but like u said.. its supposed to go in fixedupdate

zenith crown
rocky canyon
nova swift
mossy willow
rocky canyon
#

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

rocky canyon
# mossy willow 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....

▶ Play video
#

basically u dont even need to do anything besides set one to Inactive..

zenith crown
rocky canyon
#

u can test in playmode.. (just disable one camera) you'll see it transition to the next one

rocky canyon
#

if it only needs accessed within the script its contained use private

nova swift
rocky canyon
#

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

zenith crown
#

Yeah but i need to see the public ones and atm i dont see anything

rocky canyon
#

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

nova swift
zenith crown
rocky canyon
zenith crown
#

and so in the game settings before starting a save you can tweak the numbers u start with

rocky canyon
#

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

zenith crown
#

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

rocky canyon
#

you COULD but dont do it unnecessarily

#

unless it makes sense

#

theres a SOLID principals thing that we tend to use as structure

#

the first rule is Single Responsibility

zenith crown
#

It would make sense to have 2 scripts instead of 3

#

putting the Blueprint.cs in the movement.cs

rocky canyon
#

soo things shouldn't know about other things unless they have to

#

etc

zenith crown
#

makes sense

rocky canyon
#

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

zenith crown
#

Blueprints just contains all the variables the character needs to operate

#

But if i make a duplicate

#

it duplicates the settings

rocky canyon
zenith crown
#

so it would make sense to put it in the movement code right?

zenith crown
rocky canyon
#

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

zenith crown
#

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

rocky canyon
#

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

zenith crown
#

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

rocky canyon
#

i think its trying to work against ur gravity..

#

once it finally cancels out ur gravity it'll jump

wintry quarry
rocky canyon
#

may need to reset ur Y velocity to 0 right before the jump

#

if -> Jump
Yvelocity = 0;
// then do ur jump

zenith crown
rocky canyon
wintry quarry
#

Did you ever share your full script?

rocky canyon
#

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

rocky canyon
#

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

zenith crown
rocky canyon
#

alrighty.. set it back to what u had before.. and go a different troubleshooting direction

zenith crown
rocky canyon
#

put a debug back in the jump method and see if its debuggin only 30% of the time

zenith crown
rocky canyon
#

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

zenith crown
#

Wait nvm im not getting it i saw it wrong

rocky canyon
zenith crown
rocky canyon
#

i gotta go get lunch for work.. good luck 👍

zenith crown
zenith crown
rocky canyon
#

jump only working 30% of the time - user reports

#

the cat ninja deleted? 😄

zenith crown
#

Cat on keyboard is the best thing ever

wintry quarry
zenith crown
#

that js made me laugh

raw token
#

She wants dinner way too early and is being a pest

rocky canyon
#

im heavily reliant on it just working

wintry quarry
#

Also you're doing multiple Move calls per frame which is a known issue

rocky canyon
#

mentioned that earlier

zenith crown
rocky canyon
#

should just tack on ur other move vector

#

normalInputVector + newGravityVector