#💻┃code-beginner

1 messages · Page 607 of 1

acoustic belfry
#

its a prefab

rich adder
#

oh i didnt even think of this, then yeah thats def something very wrong if they are interacting with prefab still which I might suspect now

acoustic belfry
#

with they you mean me? well yea...................it is

verbal dome
#

Anyway focus on 1 issue at a time. What about this ^ @acoustic belfry

#

And make balas private, not public

acoustic belfry
acoustic belfry
#

ok

polar acorn
acoustic belfry
#

i only have one mortem (name of the enemy) in the game, (wich is the owner of the script)

thorn skiff
#

i followed the sebastian lague tutorial on procedural landmass generation but i did a finite instead of infinite, im trying to add biomes and i came across voronoi diagram but i dont know where to start.

verbal dome
polar acorn
# acoustic belfry one

Then something keeps resetting balas back to 5. If making it private worked without giving you any errors, then it looks like your Reload() function is running more than you expect

thorn skiff
verbal dome
#

Blend them with other noises

thorn skiff
#

ill try that thanks

acoustic belfry
#

now for make it worse...for an strange reason now the bullets dont move

#

this is getting worse and worse...

#

i dont know what im doing wrong

#

Q-Q

rocky canyon
#

if u have a brick wall built on a broken brick and u remove that brick to replace it..

#

what happens to the rest of the wall?

polar acorn
# acoustic belfry it didnt

So, since that means no other scripts are modifying balas, one of two things is happening:

  1. There's more than one mortem_rifle_script and you're calling disparar on different ones
  2. Reload() is resetting balas back to 5 in between each call of disparar
rocky canyon
#

😄 been there done thta

acoustic belfry
rich adder
#

doesnt help that most are not native english variables so its hard to tell wth is what

polar acorn
#

see when that logs

tight oak
#

Hiya! I'm pretty new to Unity and I was wondering if I could get a quick hand with some code:

I have all of my Enemy Health, Projectile Damage, Enemy Movement code sorted, only issue isssss, the bullets collide with the Circle Collider 2D that's ONLY being used for player-detection (the enemy will only chase the player when they're spotted)

I've managed to make the bullets ignore the player character, but I'm not sure how to make that happen with component-specific stuff

How would I go about nullifying the detection-circle from being detected in the projectile code? I'd really appreciate any advice!

acoustic belfry
acoustic belfry
acoustic belfry
#

wait, i think i did something wrong

#
        animator.Play("Base Layer.MortemRifleReload");
        reload = true;
        StartCoroutine(Reload());
    }```
that should be inside braces
#

w h a t

btw the enemy works the same, i dont know what went wrong, and also what that return means
this is what appeared, its on the PLAYER shooting script

    {
        Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mouseposition.z = 0;
        Vector3 shootDirection = (mouseposition - transform.position).normalized;

        GameObject shotgunbullet = Instantiate(shotgun_bullet, transform.position, Quaternion.identity);
        shotgunbullet.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(shootDirection.x, shootDirection.y) * shotgun_bulletspeed;

        Vector3 leftDirection = Quaternion.Euler(0, 0, -10) * shootDirection; // Giro de -10 grados a la izquierda
        GameObject leftBullet = Instantiate(shotgun_bullet, transform.position, Quaternion.identity);
        leftBullet.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(leftDirection.x, leftDirection.y) * shotgun_bulletspeed;

        Vector3 rightDirection = Quaternion.Euler(0, 0, 10) * shootDirection; // Giro de 10 grados a la derecha
        GameObject rightBullet = Instantiate(shotgun_bullet, transform.position, Quaternion.identity);
        rightBullet.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(rightDirection.x, rightDirection.y) * shotgun_bulletspeed;

    }```
slender nymph
eternal falconBOT
tight oak
#

Oh my gosh THANK YOU I've been trying to figure out for AGES why my VisualStudio wasn't VisualStudio-ing like everyone else's pikachuface

tight oak
slender nymph
#

OverlapCircle is a method you can call in Update (or where ever)

tight oak
#

Awesome! Thank you for the help, you're the best :]

acoustic belfry
#

Hi, i have good news and bad news.
I managed to fix the issues, now the bullets decrease, and the bullets move, and when it empties it enters into the coroutine where it restarts the bullet amount...
My issue now is...the reloading animation doesnt work

forest orbit
#

why can't I reference my JoinBtn here?

slender nymph
#

you can't just have arbitrary code outside of a method

polar acorn
forest orbit
#

ahhhh yea right

acoustic belfry
#

hey btw, why my animation doesn't triggers?

#

it should

        {
            animator.Play("Base Layer.MortemRifleReload");
            reload = true;
            StartCoroutine(Reload());
        }

    }```
#

this script works, cuz everything works but the animation

rich adder
polar acorn
rich adder
#

if its true why are you setting it to true again

acoustic belfry
slender nymph
#

do you assign true anywhere else? because if not, then naturally that if statement can never evaluate to true

forest orbit
#

what am I doing incorrectly here?

polar acorn
acoustic belfry
slender nymph
#

have you actually verified that line is running

acoustic belfry
#

im now gonna

slender nymph
#

but also, like nav pointed out, that assignment to reload is 100% pointless there

acoustic belfry
#

yep it works

slender nymph
#

wdym "huh"? reload is already true there, it is pointless to assign true to reload there

polar acorn
acoustic belfry
#

listen, i checked the log, and it works, the whole bool works

#

the issue here is, the animation doesnt

slender nymph
#

nobody is saying that the bool doesn't work. we're pointing out that assigning true to it there is pointless.

#

you're literally doing if reload is true assign it to true

acoustic belfry
#

i...didnt saw that

#

sorry

slender nymph
#

then pay attention to what people tell you

acoustic belfry
#

but well, that's fixed, but what's not is, why the animation doesnt run?

slender nymph
#

anyway, show your entire console window when you see the log that proves your animator.Play line is running

acoustic belfry
slender nymph
#

stop hiding your warnings

acoustic belfry
#
       {
           Debug.Log("reload scene");
           animator.Play("Base Layer.MortemRifleReload");
           StartCoroutine(Reload());
       }

   }```
lethal smelt
acoustic belfry
slender nymph
acoustic belfry
lethal smelt
#

well maybe it is

#

but it'll def be better than this

acoustic belfry
lethal smelt
acoustic belfry
slender nymph
acoustic belfry
slender nymph
#

show it

acoustic belfry
#

ok

slender nymph
#

also turn off collapse mode so that the logs are shown in the proper order

acoustic belfry
#

ok

lethal smelt
#

oh now that I'm looking at it...unity 6 looks a lot diffrent huh

acoustic belfry
lethal smelt
#

I still haven't updated yet lol

acoustic belfry
#

it says there's an animation issue for the Tuetue (bird meele-based enemy)

#

nothing about the Mortem (proyectile-based enemy and the one highlater btw)

polar acorn
#

Well there's like 900 of them, did you consider maybe some of them are related to the one that isn't playing the animation

lethal smelt
#

I think the controller in animator component is empty

acoustic belfry
lethal smelt
#

unity does this to me too every now and then

slender nymph
#

address that then try again

acoustic belfry
# slender nymph there are 900 of them though

i meant, i clicked all of them, :<
originally where of the Mortem and the Tuetue, but then i fixed something, and the error faded away...but the reloading animation's still missing

verbal dome
acoustic belfry
slender nymph
#

or just fix that issue and try again with collapse disabled since we want to see when any warnings happen around that specific log that shows when you call animator.Play on the shooting object

acoustic belfry
#

oh, it was that i forgot to add it to the object
o - o

#

xd

#

But now i have another issue..................................................
the animation executes, but doesn't wait till it ends to return to shooting, and then gets in a loop of "reloading" and "shooting" at the same time

#

but hey, its an advancement

slender nymph
#

okay do you have any logic that prevents it from shooting during the reload animation?

acoustic belfry
#

w e l l

#

no

acoustic belfry
#

in theory

#

i mean, it needs bullets to do it, and thats earned in the coroutine, "wich says that it would give the bullets to the enemy after the animation ends"

#

but doesnt work

#
    {
        while (reloadAnimation)
        {
            yield return null;
        }
        reload = false;
        balas = cantidadDeBalas;
        //done reloading
    }
}```
polar acorn
#

What changes reloadAnimation

acoustic belfry
#

its supossed to be the animation...looks like i did it wrong

#
        if (reload == true)
        {
            Debug.Log("reload scene");
            animator.Play("Base Layer.MortemRifleReload");
            reloadAnimation = animator.GetCurrentAnimatorStateInfo(0).IsName("MortemRifleReload");
            StartCoroutine(Reload());
        }```
polar acorn
#

You just set the animation to MortemRifelReload. You already know exactly what the current animation is. Why not just set reloadAnimation to true there?

#

Code runs, one line at a time, top to bottom

acoustic belfry
#

wat

polar acorn
#

You set the animation, then on the next line immediately check the animation

acoustic belfry
#

yeah

polar acorn
#

it's going to be what you just set it to

#

why bother checking it there

acoustic belfry
#

i dont get it

#

ah, im checking it

#

for make the coroutine also check it

#

and wait till it ends

polar acorn
#

Okay, let me ask you a question.

int x = 7
bool isXSeven = x == 7
#

Is there any universe in which isXSeven is false

acoustic belfry
#

no...

swift crag
#

I think you misunderstand what this line of code does

#
reloadAnimation = animator.GetCurrentAnimatorStateInfo(0).IsName("MortemRifleReload");
#

This does not perpetually check if the current animation is "MortemRifleReload", over and over

#

It checks if, at this moment in time, the current animation state name is "MortemRifleReload"

#

That's it.

#

It doesn't matter if the animation state changes sometime later

#

reloadAnimation will remain true

acoustic belfry
#

o h

#

then what i should do for acomplish what i need?
make that when bullets reach zero (reload becomes true) executes an animation, and waits until that animation ends for make bullets return to it original value

swift crag
#

perhaps you should do something to make reloadAnimation become false there

acoustic belfry
#

ooooooh, now i get it

#

but the issue is.........................what? specificly
sorry for my noobness

swift crag
#

You already know how to check if the current animation state is named "MortemRifleReload"

#

you have explicitly written a line of code that does this

acoustic belfry
#

yeah, i know that, but i want to do the oppositive...

#

im getting pretty lost here

swift crag
#

but in this case, I'm pretty sure you do just want

acoustic belfry
#

what does this? i thought it detected till the bool reloadAnimation, wich is the equivalent to the animation, ended
yield return null;

acoustic belfry
swift crag
#
while (condition) {
  condition = ...
  yield return null;
}
swift crag
#

yield is a keyword used inside an enumerator method

#

it causes the enumerator to stop and either exit completely (yield break) or produce a value yield return)

#

with Coroutines, you generally just yield return nothing -- thus, yield return null

#

Unity resumes the method once every frame. When the method hits a yield, it stops again.

acoustic belfry
#

so for now i just wrote it just as a decoration

swift crag
#

it is very important

#
while (true) {

}
#

This will freeze your game

#

It runs forever.

acoustic belfry
#

aaaaaaaaa

#

got it

swift crag
#
while(true) {
  yield return null;
}

If you run this as a coroutine, it will run the loop once per frame

#

it hits yield return null and stops

#

then Unity resumes it one frame later

#

You should check if the animation is still running once per frame

#

Once it is no longer running, you can exit the loop

acoustic belfry
#

but how do i do that?

#

thats what im seeking and what i thought i did well

swift crag
#

you already know exactly how to check if the animation is running

acoustic belfry
#

the thing

#

but how do i exit the loop?

swift crag
#

a while loop terminates when its condition becomes false

acoustic belfry
#

cuz it looks like, atleast when i try it, that doesnt ends, and the mortem is just there having a seizure trying to reload an infinitely empty rifle

swift crag
#

you can update the variable you're using as its condition inside the loop

acoustic belfry
#

ooooooooooooooooooooooooooh

swift crag
#
bool whatever = true;

while (whatever) {
  whatever = Time.frameCount == 1000;
  yield return null;
}
acoustic belfry
#

but i want that time to be the exact of the animation

swift crag
#

this will run until the frame count is 1000, and then the loop will exit (one frame later, actually, due to the order I put things in)

swift crag
acoustic belfry
#

oh, ok

acoustic belfry
#
    {
        while (reloadAnimation)
        {
            reloadAnimation =! animator.GetCurrentAnimatorStateInfo(0).IsName("MortemRifleReload");
            StartCoroutine(Reload());
            yield return null;
        }
        reload = false;
        balas = cantidadDeBalas;
        //done reloading
    }
}```
swift crag
#

this checks if the reload animation is not "MortemRifleReload"

#

then it...starts another coroutine

#

get rid of StartCoroutine entirely and don't negate the IsName check

polar acorn
#

Like, what did you think adding that line would accomplish

acoustic belfry
#

eh, looks like i didnt realized

polar acorn
#

Read your code as your typing it

acoustic belfry
#

aaah, that thing came with the paste

polar acorn
#

every line does something

acoustic belfry
#

i copy pasted a thing from another

acoustic belfry
acoustic belfry
acoustic belfry
polar acorn
unborn valley
#

i've been re-reading some of my old Java code, turns out old me did NOT know about indenting or spaces. i legit typed stuff like this

if(posX-15<0){posX=16; xAccel=(1-xAccel)/2;}
if(posX+15>width){posX=width-16; xAccel=(1-xAccel)/2;}
if(xAccel>15){xAccel=15;}
if(xAccel<-15){xAccel=-15;}
if((abs(xAccel)<1)&&(!right)&&(!left)){xAccel=0;}

THIS PHYSICALLY HURTS TO READ WHAT

polar acorn
polar acorn
unborn valley
#

damn

#

yea im keeping that one lol

acoustic belfry
#

i feel like im doing something wrong

swift crag
#

if you don't understand what any of the code you're writing is actually doing, then you seriously need to stop what you're doing and use something like !learn to get a handle on this

eternal falconBOT
#

:teacher: Unity Learn ↗

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

polar acorn
#

What value are you reading and setting that boolean to

acoustic belfry
polar acorn
#

in the loop

#

what are you setting it to

acoustic belfry
#

aaah, same

#
    {
        while (reloadAnimation)
        {
            reloadAnimation = animator.GetCurrentAnimatorStateInfo(0).IsName("MortemRifleReload");
            yield return null;
        }
        reload = false;
        balas = cantidadDeBalas;
        //done reloading
    }```
#

i feel like im doing something wrong

#

wrong af

polar acorn
#

Okay, and what does this mean:

animator.GetCurrentAnimatorStateInfo(0).IsName("MortemRifleReload")
#

What is this checking?

acoustic belfry
#

if the state is reload

#

originally i set it to null in the corountine

#

the oppositive

#

but i decided right now to change it to positive

#

for test if that may help

#

it didnt help

unborn valley
swift crag
#

It checks if the current animation state is named "MortemRifleReload" and stores the result in reloadAnimation

#

If that ever becomes false, the loop ends

verbal dome
#

The issue here might be that the animation state doesn't really change instantly when you call Play, but at the end of the frame or in the next frame instead

#

But your code expects that it does

tiny oxide
#
if (playerRb.linearVelocity.y < 0)
{
    isFalling = true;
}
else
{
   isFalling = false;
}
Debug.Log(playerRb.linearVelocity.y);

I have a player's rigidbody that is affected by gravity, yet its linear velocity stays at 0 when it is moving downwards. What am I missing?

#

I expected the linear velocity to become negative

swift crag
wintry quarry
#

Also you should log that value with a label so you know what you're looking at in the logs

#
Debug.Log($"Velocity is {playerRb.linearVelocity.y}");```
acoustic belfry
#

i got lost

tiny oxide
#

And it's on in the rigidbody, let me go ahead and send you the script.

#

using System;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Rigidbody playerRb;
    private BoxCollider boxCollider;

    public GameObject propeller;

    private float gravityModifier = 25.0f;
    private float verticalSpeed = 10.0f;
    private float horizontalSpeed = 5.0f;
    private float propellerSpeed = 10.0f;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        Physics.gravity *= gravityModifier;
        playerRb = GetComponent<Rigidbody>();
        boxCollider = GetComponent<BoxCollider>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        // Gets player input
        float horizontalInput = Input.GetAxis("Horizontal");
        float jumpInput = Input.GetAxis("Jump");

        // Applies force upwards
        float verticalForce = jumpInput * verticalSpeed;
        playerRb.linearVelocity = new Vector3(playerRb.linearVelocity.x, verticalForce, playerRb.linearVelocity.z);

        // Applies forces horizontally
        float horizontalForce = horizontalInput * horizontalSpeed;
        playerRb.linearVelocity = new Vector3(horizontalForce, playerRb.linearVelocity.y, playerRb.linearVelocity.z);

        // Spin the propeller respective to the player's vertical velocity
        propeller.transform.Rotate(Vector3.up * verticalForce * propellerSpeed);

        Debug.Log($"Velocity is {playerRb.linearVelocity.y}");
    }

}


wintry quarry
#
playerRb.linearVelocity = new Vector3(playerRb.linearVelocity.x, verticalForce, playerRb.linearVelocity.z);```
#

verticalForce is 0 if there's no input on the Jump axis

tiny oxide
#

I see, makes sense.

wintry quarry
#

You should be seeing this in the form of really unrealistically slow falling

tiny oxide
#

Should I make an if statement to not change the linear velocity if the jump input is 0?

#

Seems reasonable.

wintry quarry
#

that would be pretty normal yes, only jump if you're jumping

warm owl
#

Hello, i have a little bit of problem. i made a settings in my game, a pretty simple one. and i dont really understand why for example ticking in the checkbox to change from windowed mode to full screen. works one way, but the other dont.

#

So only the set value is working which i set in the inspector

wintry quarry
tiny oxide
swift crag
#

you'll need to record an MP4

warm owl
#

ah

#

finally

#

public void SetFullscreen(bool isFullscreen)
{
    Screen.fullScreenMode = isFullscreen ? FullScreenMode.FullScreenWindow : FullScreenMode.Windowed;

    PlayerPrefs.SetInt("Fullscreen", isFullscreen ? 1 : 0);
    PlayerPrefs.Save();
}

rich adder
drifting cosmos
#

!cs

eternal falconBOT
warm mason
#

hi guys, i've been learning C# recently and i have a question, when / how much do i need to know before switching over to unity

#

i have a good concept of all the fundamentals, i am comftorable with OOP, etc.

#

is that all I need to start making games?

wintry quarry
warm mason
#

cuz

#

i mean

#

surely you'd have to learn the syntax and basics on what you're looking at like, whats a class, whats a method, learn about inheritence, how to store data and what different data types are, etc.

#

or

#

i guess you could just learn it through unity but

#

if you look up a unity tutorial, they never teach you that stuff they just tell you what code to put you konw?

#

idk

#

do you think the part for me now is just learning the different classes/methods Unity uses and how to incoperate that into my game?

drifting cosmos
blazing ice
#

what do you mean the reference isnt set to an instance of an object i clearly set it in the start() function....

blazing ice
#

no i keep forgeting rigidbody 2d is different from standard rigidbody thats the reason why lol

#

i hate 2d!!!

drifting cosmos
blazing ice
#

im just used to the way 3d works so small errors like typing the wrong rigidbody makes the code break and i dont realize it lol

drifting cosmos
#

oh

eternal falconBOT
rich ice
#

also make sure the numbers on the side are visible (if you do send a screenshot). we cant really figure out where the error is if we dont know what line its on

blazing ice
#

i mean i know how to paste code i just didnt think it'd be needed considering the tiny amount i wrote

#

i already solved it so its fine

lusty star
#

Yeah its some pretty tiny amount i agree with anime person

rich ice
#

"anime person" skully

rich ice
#

in the screenshot they sent, we cant see which line the error is on. we can take a guess, but its still a lot easier if we can just see the numbers on the side

topaz mortar
#
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());```
What is the difference between these two?
I understand the first uses the old input system and the 2nd the new input system, but what does that actually mean?
#

I'm using the new input system for my player movement with the keyboard too, but I don't understand how this translates to the mouse? Since I haven't set up the mouse in my inputs?

timber tide
#

There's a thing called an Event System on your scene where these input events are setup

topaz mortar
#

Hmm, I remember that should be there, but it's not?

#

I'm using this, but haven't set up anything for the mouse, or is that just already included?

timber tide
#

Uh, make a ew game object and add EventSystem and Input Module if it's not automatically added

topaz mortar
timber tide
#

Ah, thought you were saying it didnt work. Actually maybe you don't need it for coordinates now that I think about it

topaz mortar
#

Ah no, it works, I just don't understand how lol

timber tide
#

Input class is legacy, but it includes standard properties

topaz mortar
#

I'm using this one now:
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());

#

But from setting up the keyboard movement, I thought I had to catch a mousemove event or something

#

like for keyboard movement I'm doing:

{
    _moveInput = inputValue.Get<Vector2>().normalized;
}```
timber tide
#

Right, Mouse.Current is based on the newer input system, but you can still use the legacy too.

astral falcon
#

highly advice to go to the new one tho. and mxiing both sounds even worse

topaz mortar
#

I just posted the first line as example, I'm trying to use the new system

timber tide
#

I use legacy for when I can't be bothered mapping keys

#

old fashion poll your input

topaz mortar
#

I wonder why this line works, without me setting up the input in my input asset:
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());

#

where does "Mouse" come from?

timber tide
#

It's some standard property. Unity recognizes your device and input from your mouse

topaz mortar
#

So would this work for controllers too?

timber tide
#

That exact property? Doubtful

#

Kinda where the 'new' input system shines though where you can have multiple different controller profiles that map similar operations

topaz mortar
#

So how do I set this up with the new input system?

#

Because I thought I was using the new input system with this

timber tide
lavish magnet
#

How would you guys recommend coding a rolling barrel? I ahve a capsule collider and kinematic rigidbody on it? just manually add to the rotation and position in FixedUUpdate?

topaz mortar
naive pawn
lavish magnet
#

that one

#

And at the same time, The text is a child of the barrel

#

So when i rotate the barrel, how should i go about keeping the text still?

topaz mortar
#

I think you can fix the text by freezing it's position?

lavish magnet
#

like i want it to move with the barrel but not rotate as the barrel does

#

shoould i just not have it as a child?

#

My text doesnt have a rigidbody

topaz mortar
#

yeah just figured lol

naive pawn
lavish magnet
#

I may try tht

hollow niche
#

"Can't add script Example.cs because class name cannot be found" error when trying to add the script to my object. How do I fix it?

And yes, the class name in the file and the file name matches

formal jungle
#

Then because of people like you, others see that these specific channels are dead and dont bother posting their question

#

or they act like you and post their questions in general thus creating a vicious cycle

topaz mortar
formal jungle
#

i am just showing you how to use the server...

fickle plume
#

@formal jungle You were already warned yesterday for starting disruptive discussions. They were directed to proper channel already, if they continue ignoring directions then alert moderators.

formal jungle
#

ohhh sorry i didnt see that other user already mentioned that

#

my bad

charred spoke
lusty star
chrome apex
#

so does my method where I save playerprefs need to be static in order to reference it in another script?

chrome apex
#

so why doesn't GetString work for me? Says key doesn't exist

lethal smelt
#

just know that their values get reset after you build

chrome apex
chrome apex
#

private void Awake()
{
PlayerPrefs.GetString(levelsPassed);
}

#

that's all lol

#

do you want the saving script?

lethal smelt
#

its suppose to be PlayerPrefs.GetString("levelsPassed");

chrome apex
#

oh

#

it's always something stupid...

#

thanks, it works

lethal smelt
#

oh wait unless you alrady declared that as string before

#

that could work too

chrome apex
#

well I did

#

I mean, I'm required to, aren't I?

sand gate
#
    public int newH;
    public GameObject[] hbar = new GameObject[5];
   public void DrainHealth() {
        health -= 10;
        newH = health;
        if (health <= 0) {
            Destroy(gameObject);
        }
    }
    public void Update()
    {
        GameObject[] hbar = GameObject.FindGameObjectsWithTag("h");
    if (newH < health) {
        Destroy(hbar[hbar.Length - 1]);
     }   
    }``` whats wrong w this code?
#

there are 5 triangles in the scene w tag "h"

#

i want to destroy one as the health decreases

rich ice
#

remember to post your !code correctly

eternal falconBOT
rich ice
#
public int health = 50;
public int newH;
public GameObject[] hbar = new GameObject[5];
public void DrainHealth()
{
    health -= 10;
    newH = health;
    if (health <= 0)
    {
        Destroy(gameObject);
    }
}
public void Update()
{
    GameObject[] hbar = GameObject.FindGameObjectsWithTag("h");
    if (newH < health)
    {
        Destroy(hbar[hbar.Length - 1]);
    }
}

should look like this

sand gate
#

alright

chrome apex
rich ice
sand gate
#

no triangle is getting destroyed

slender nymph
sand gate
#

OH

#

wow

#

alr

#

ill see

#

thankyou

#

how do i make it

#

update then

fierce shuttle
# chrome apex so why doesn't GetString work for me? Says key doesn't exist

This could depend on when your trying to access your pref, it sounds like you might be trying to access a key that doesnt exist in prefs yet, though without seeing the full error, my suggestion would be to try checking if the key exists first, PlayerPrefs has a function for that: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/PlayerPrefs.HasKey.html - if you are stil having issues, post the full error message your getting and your full script with where you are calling your sets and gets, and im sure someone can provide more info for you

slender nymph
sand gate
#

oh

#

i see what youre saying

#

let me try

slender nymph
#

please finish a thought before sending a message. we don't need you to spam a single thought across 5 different messages

fierce shuttle
# chrome apex already fixed

Ah good to hear, though out of curiosity, what kind of data are you trying to save with PlayerPrefs? Is it just 1 or 2 simple values?

sand gate
#

this is the error i am getting

slender nymph
#

why do you need to do that, just use a List that you populate in the inspector. then just remove the objects from the list when you destroy them. using any of the Find methods in update is terrible

sand gate
#

alright

slender nymph
#

show the stack trace for that exception

sand gate
slender nymph
chrome apex
#

it's webgl anyway so I think I can only use playerprefs for it

rich ice
sand gate
slender nymph
#

huh? show the full stack trace

sand gate
#

the triangles are being destroyed, however the last one remaining isnt , ill work on it.

slender nymph
#

well if you do what i suggested instead of using Find then you won't need to sort the array

astral falcon
#

maybe show your code abot sorting. I guess, you are missing the actual sorting comparison

sharp jolt
#

Hi, I Can't find this where this error is, Unity is letting the game run and it runs perfectly fine so far no bugs or anything but i get this error about 200 times per second

slender nymph
#

You probably need to assign the root variable of the PlayerCharacter script in the inspector.

sharp jolt
#

Oh wait i swear that root variable didnt exist there before 😭

#

i was looking for it for so long

astral falcon
sharp jolt
visual palm
#

Does anyone know why I can't place the script on the inspector ?

rich ice
#

the script needs to be on an object

polar acorn
#

You need to drag in an object with the script on it. That object then becomes the PlayerMovement instance

echo ruin
visual palm
compact stag
#

guys, i have this line of code, I wanted to make it so that the input field isnt empty, however, it always returns object reference not set to an instance of an object

    public void PlayGameStart() {
        if ( nameInput.text != null ) {            
            SceneManager.LoadScene(1);
        } else {
            
        }
    }
slender nymph
compact stag
polar acorn
# compact stag

This one has that set, so this isn't the one throwing the error. Look at the other instances of this script

compact stag
slender nymph
#

how have you confirmed that

polar acorn
compact stag
compact stag
slender nymph
#

prove it by searching t:Singleton in the hierarchy while this error is appearing

polar acorn
compact stag
#

oh, this was applied on the canva 🤦‍♂️

slender nymph
#

this is why you should always verify your assumptions

compact stag
#

i mustve applied it by mistake, im sorry guys

compact stag
#

i ran into another problem that the game still starts even if the input field is not empty but i want to fix this by myself

#

thank you guys!!

slender nymph
grand snow
#

string.IsNullOrEmpty() can be used to easily check myStr != null && myStr != "" @compact stag

compact stag
#

i was about to say that!

#

im gonna use it

slender nymph
#

IsNullOrWhiteSpace is typically better

compact stag
#

how come?

slender nymph
#

because it checks if the string is only whitespace too

grand snow
#

depends on the source of the string. I would use Trim() any input and then check for empty state

slender nymph
#

string.IsNullOrEmpty(" "); is false
string.IsNullOrWhiteSpace(" "); is true

slender nymph
#

better to Trim only after ensuring that the string isn't just empty, null, or whitespace. because you have to first ensure it isn't null before trimming anyway

grand snow
#

meh i dont think its bad unless we are working with some massive string

slender nymph
#

Sure it's not bad, and neither is calling GetComponent every frame, it's just not necessary to trim before ensuring there actually is any input

compact stag
#
    public void PlayGameStart() {
        if (!string.IsNullOrWhiteSpace(nameInput.text)) {            
            SceneManager.LoadScene(1);
            Debug.Log("true");
        } else {
            Debug.Log("false");
        }
    }
}

final code!

#

actually

#

I wanted to ask a question, its gonna be a bit hard to explain but

i have two scenes, the menu that has a gameobject called datamanager and the other one scene is called game

I have a text called User in the game scene, I made a public variable in my singleton script thats attached to my datamanager, however, how do I instantiate the user text in my singleton script?

#

should I use .Find? I heard its not the best way to do stuff

burnt vapor
#

It's not

#

I assume the user text is a UI component that you want to instantiate? I would just keep the UI ready without any extra instantiation if I were you

#

Keep references in a class close to the UI which holds the UI elements you want to access, then get a reference from that class so you can update the UI elements

#

This is an easy way to get everything together in one organized class and then you don't put it all in a manager that isn't just for UI

compact stag
burnt vapor
#

You can use a Find method to get that UI class, but you can also just make that a singleton

compact stag
#

yeah, its already a singleton

#

is it okay to use .find in a singleton script?

burnt vapor
#

Find is messy because it's slow and prone to cause issues so you should not use it

forest orbit
#

why is my anchor thing missing?

burnt vapor
#

Why not just use a singleton?

timber tide
forest orbit
#

nope that fixed it ty

twin pivot
#

commenting one for loop out makes it work

#

but when i have both they dont work

lethal smelt
#

I wonder if it'll work if you replaced i with j for 2nd loop

twin pivot
#

tried that

#

did not work

blissful mason
twin pivot
#

its playing the for loop 40 times before it moves onto the next

wintry quarry
# twin pivot

what are you trying to do here? This looks overcomplicated and yes the loop is actually pointless because it all happens in one frame

wintry quarry
twin pivot
#

ah i see

#

im stupid

blissful mason
wintry quarry
#

you need a coroutine here or to just rotate once per frame in update and then reverse direction after a certain amount of time has elapsed or a certain number of degrees

twin pivot
#

alright thanks

burnt vapor
eternal falconBOT
wintry quarry
#

a loop in Update does not make sense for this

polar acorn
# twin pivot

Loops run to completion. Literally nothing else in the entire program will run until the loop ends

twin pivot
#

i see

polar acorn
#

That includes drawing anything, updating any transforms, running other scripts

twin pivot
#

what should i use instead then

polar acorn
#

Code runs one line at a time, top to bottom

twin pivot
lament stag
#

hey guys. I wanted to know how to make trigger sensitive input in unity?

twin pivot
#

to run

polar acorn
lament stag
#

like for now it only takes 0 and 1

wintry quarry
# twin pivot

more like something like this

float rotation;
float speed = 40;
float maxRotation = 40;

void Update() {
  rotation = Mathf.MoveTowards(rotation, target, speed * Time.deltaTime);
  transform.localEulerAngles = new(0, 0, rotation);

  // reverse direction
  if (Mathf.Abs(rotation, maxRotation) < 0.01f) {
    maxRotation = -maxRotation;
  }
}```
rich adder
polar acorn
#

that would include updating the object's rotation visually

#

So that would mean you want the rotations to perfectly cancel out and achieve nothing

lament stag
rich adder
polar acorn
# twin pivot ah i see

The Update function is one frame. It is the definition of what a frame is. The frame is rendered after every object's Updates finish running. Until an object's Update finishes, the frame cannot finish. You can never see the "intermediate state" of an Update.

twin pivot
#

ah i see

polar acorn
#

If you rotate an object 10 degrees left in update, then rotate it 10 degrees right in the same update, those both happen in the same frame

#

meaning nothing happens

lament stag
twin pivot
#

so the entire thing is happening in one frame

wintry quarry
#

as we have been saying yes

#

that's what update is

#

a single frame

twin pivot
#

and here is my ass thinking it was just hyperbole for "really fast"

wintry quarry
#

no it's literally "this runs once each frame"

polar acorn
#

That is, in fact, stated plainly on the default script template:

twin pivot
#

is there any way to go back to a certain line then?

polar acorn
#

no

#

Update is the frame

#

you cannot separate it across frames

#

It is the literal definition of what a frame is

twin pivot
#

no i mean

#

i take it out of update

#

but another way of looping it

polar acorn
twin pivot
#

not what id need to do

polar acorn
#

With a coroutine, or one frame at a time by tracking time in update

astral falcon
swift crag
#

A coroutine lets you write a method that can pause itself and get resumed later.

twin pivot
swift crag
twin pivot
#

yay......

twin pivot
#

someone stab me

swift crag
#

if you hate learning new things, then you're in the wrong line of work

twin pivot
#

oh no i love learning new things

#

i love sarcasm a little more tho

dusty nimbus
#

Coroutines are easy and powerful once you start using them! ^

rich adder
#

they're ok. Not "powerful"

#

true power is pure async

swift crag
#

if you need to run a method across many frames, coroutines are great

rich adder
#

Awaitable has entered the chat *

swift crag
#

I pass Awaitables to StartCoroutine 😛

rich adder
#

I just hate that Coroutines cannot have return values for example

twin pivot
#

me and coroutine are gonna be great friends

astral falcon
#

Also the ability to jump back to mainthread

rich adder
#

yeah swapping threads is cool when dealing with unity main loop only API

swift crag
#

it's pretty nifty

#

I used Awaitable in one project to allow me to interleave game logic (e.g. moving a unit) with visuals (e.g. slowly moving the unit's sprite between the start and end positions)

dusty nimbus
#

Okay now I want to learn about awaitables - they sound a lot more useful than a coroutine 😆

swift crag
#

If I was just calculating a new game state (and not actually showing the sequence to the player), I skipped over the visuals and instantly returned

#

It worked out really nicely

rich adder
#

but def do learn awaitable cause its great especially if you're stuck between coroutine and traditional async

#

unity has entry methods for both
IEnumerator Start()
async void Awake()

polar acorn
#

There's basically a power scale of delaying things,
Coroutines are like base form Goku, Awaitables are Super Saiyan, and async is Super Saiyan Blue. ||Invoke is Yamcha||

astral falcon
#

I based my entire state management on awaitables, calling other substates and so on. I did not even touch coroutines again since then 😄

rich adder
#

the grabbing directly into assets is kinda handy ngl

#

I heard unity is strange with HTTPClient idk if it still applies

astral falcon
cosmic dagger
astral falcon
#

So what would be InvokeRepeating be? 😄

rich adder
dusty nimbus
#

So a Coroutine would use something like Wait X Seconds where an Awaitable is just like 'When I'm done I'll come back and we can carry on?'

astral falcon
twin pivot
#

wait

rich adder
#

good enough 😄

twin pivot
#

can there be 2 yields in 1 coroutine

rich adder
#

you can have as many yeilds you want

astral falcon
wintry quarry
twin pivot
wintry quarry
#

that's crazy

#

start it in Start

rich adder
#

oh my..yeah starting one every frame not good lol

astral falcon
#

thats a lot of swinging going on tho, sounds like a good party 😄

rich adder
#

they will be fighting eachother setting values (dont ask me how I know)

wintry quarry
#

also it's looking to me like your IDE is not configured @twin pivot

#

You should get it configured so you get autocomplete and error highlighting

#

!ide

eternal falconBOT
twin pivot
#

yea i keep trying to do that

#

it just doesnt want to work

wintry quarry
#

you're probably missing a stepo

twin pivot
#

i'll do it after i finish this

rich adder
twin pivot
#

but only once

#

well i guess thats expected

wintry quarry
#

rotate right

#

then rotate left

#

then it's over

rich adder
#

like regular method it only runs once

twin pivot
rich adder
#

you can put a while loop inside

#

in coroutines they wont stop other lines from running

wintry quarry
#

(as long as there is a yield inside the loop)

astral falcon
#

and it can ever exit 😉

rich adder
#

yeah thats very important ^

#

or you will have a baaaaad time

astral falcon
#

unity will tell you otherwise by not telling you anything anymore 😄

rich adder
#

Daddy went to store to get cigarettes...

twin pivot
#

yea i definitely knew that

swift crag
#

As far as you are concerned, a coroutine is a method that you can pause and resume

twin pivot
#

opens task manager

rich adder
#

RAM usage 📈

twin pivot
#

i think i just corrupted my save file

astral falcon
#

the scene file?

twin pivot
#

nope

#

the project file

#

its not in there anymore

rich adder
#

what is "the project file"

astral falcon
#

the visual studio file?

#

there is no unity project file

twin pivot
#

in the unity hub

rich adder
#

thats not a file

astral falcon
#

Ah well, just re add the folder

rich adder
#

its just the root of your project folder

#

you can delete the entry without deleting the project

twin pivot
#

well thats the thing

#

i didnt delete the entry

#

it deleted itself

rich adder
#

oh did you move project maybe ?

#

either way, the project is still there

twin pivot
#

ah found it

#

thanks

#

oh god

#

it rolled back

#

lost like an hour of progress

rich adder
#

reminder to always hit save shortcut

twin pivot
#

oh wait

#

im using yield in start

polar acorn
#

Why are you starting the coroutine every frame

#

This is just a really really circuitous method for putting StartCoroutine in update again

twin pivot
#

thats a very good question

#

and one that i dont have an answer to

wintry quarry
# twin pivot

all you needed to do was wrap all the swinging() code in that while loop. Not add a random while loop to start

twin pivot
#

YES

#

MY BUTTON IS NOW WIGGLING

lethal smelt
#

yk
what if you just make this animation with condition instead of all this code

steep hollow
#

how do i make an or in these onWall = Physics.CheckSphere(WallCheckLeft.position, WallDistance, Wallmask) || (WallCheckRight.position, WallDistance, Wallmask);

twin pivot
wintry quarry
polar acorn
rich adder
twin pivot
#

i dont know the normal way of doing this

polar acorn
#

you can't just or the parameters

steep hollow
steep hollow
#

thx

wintry quarry
#

and to OR the results of them

swift crag
#

I would just snap that line in half

#
bool leftWall = Physics.CheckSphere(WallCheckLeft.position, WallDistance, Wallmask);
bool rightWall = Physics.CheckSphere(WallCheckRight.position, WallDistance, Wallmask);

bool wall = leftWall || rightWall;
#

jinx

#

There's no reason it can't all go on one line

#

but it's too long. icky.

wintry quarry
wintry quarry
#

but that's a micro optimization 😛

swift crag
#

if only C# had lazily-evaluated expressions

lethal smelt
#

like python

swift crag
#

python does not have lazy evaluation

polar acorn
lethal smelt
#

then what does

swift crag
#

Haskell delays evaluation until it's necessary, i believe

#

it's not super common (you usually have to do it explicitly, like by writing a zero-argument anonymous function that performs the calculation)

#

a "thunk"!

grand snow
#

"my fps is 2 but it works!" ™️

rocky canyon
#

niice

strange tapir
#

am i misunderstanding how "linear velocity" works?

    public void FixedUpdate()
    {
        Debug.Log(_body.linearVelocityY);

        // Bird rotation
        // Idk why unity does this
        _rotation = Mathf.MoveTowardsAngle(_rotation, _rotationAngle, _rotationSpeed);
        transform.rotation = Quaternion.Euler(0, 0, _rotation);

        if (_body.linearVelocity.y > _rotationSwitch)
        {
            _rotationAngle = _downwardAngle;
        }
    }

    public void OnJumpPressed(InputAction.CallbackContext context)
    {
        // Apply jump force
        // Only when the button is first pressed.
        if (context.started)
        {    
            _body.linearVelocityY = _jumpForce;
            _rotationAngle = _upwardAngle;
        }
    }```

i have this player script, and i was checking linear velocity... and it NEVER reaches 0? it keeps on going into the minuses

i thought since i have gravity pulling the player down at all times, itll reset when i jump, but it doesnt..
#

uhh this is my rigidbody setup

#

pretty sure its literally the default 😭

polar acorn
strange tapir
#

im checking specifically if it reaches -0.7

#

but it ALWAYS is

polar acorn
strange tapir
#

i see

#

i was just confused as to why its always so low

#

-8.81 shouldnt be possible to reach

polar acorn
strange tapir
#

since the player is constantly jumping and the velocity should be set to 3.35

#

and IVE never seen it be set to 3.35

#

...oh my god im working in FixedUpdate()

#

the issue is that i was trying to do something when the player is FALLING (usually meaning negative velocity) but that doesnt seem to work

twin pivot
#

how do i add force in 2d?

#

oh basically same as 3d

rocky canyon
tropic agate
twin pivot
wintry quarry
#

forces are for the Rigidbody

twin pivot
#

ah

#

im reading the 2d rigid body article in unity

#

but i dont really understand it

wintry quarry
#

what don't you understand

twin pivot
#

i cant find an example prompt of it

opal kernel
#

hi, im starting to learn c# and is code monkey's tutorial good?

wintry quarry
twin pivot
wintry quarry
#

he will teach you how to use and be dependent on his own libraries and such, not to learn C# and Unity in general

opal kernel
#

ok

opal kernel
polar acorn
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

twin pivot
#

rigidbody2D.AddForce(new Vector2(x force, y force), ForceMode2D.impulse/force);

rocky canyon
wintry quarry
#

that's an AddForce call

#

that's how you add a force to the Rigidbody

opal kernel
rocky canyon
#

Welcome to this introduction to game development. We'll be starting from the beginning, so no prior knowledge of programming or the Unity game engine is required.

Unity can be downloaded here: http://unity3d.com/get-unity

Watch episode 01: https://youtu.be/9iCnjdXEfMA

If you'd like to support these videos, you can make a recurring monthly don...

▶ Play video
opal kernel
#

ok

twin pivot
#

how would you rate vegetarian zombie

rocky canyon
rocky canyon
rocky canyon
#

rb.AddForce(Vector2.up * forceAmount, ForceMode2D.Force); //gradual force

rb.AddForce(Vector2.up * forceAmount, ForceMode2D.Impulse); // Instant force

twin pivot
#

yea

rocky canyon
#

rb.velocity = new Vector2(moveX, moveY) * moveSpeed; u can also set velocity

#

theres other modes too but impulse and force are the two i use most often

rocky canyon
# cold mist its a pretty good playlist

its a great playlist..
nice simple..
straightforward..
no fluff or clickbait stuff..

it really helps break down the very first fundamentals u need to know

  • variables
  • methods
  • classes
    and so on
cold mist
#

watched all of it and it was pretty great

rocky canyon
#

alot of the other game-type videos are like:
"so u wanna make a game?"
"let me show u how to throw crap together that u dont understand in less than 15 minutes to make a game!"

#

you wont understand it but it'll work! 😄

rocky canyon
cold mist
#

all of it

#

did unity essentials too

#

that the other guy recommended

rocky canyon
#

heck ya, ur on a roll

cold mist
#

was looking for a time yall were online

#

so i could say thanks

#

thanks

rocky canyon
#

🧡 anytime!

#

as long as i see ppl putting in some effort im always willing to help if i got time 🙂

rocky canyon
cosmic dagger
#

in the shadows . . .

rocky canyon
#

the depths of discord 🌊

sharp jolt
#

what does this mean?

polar acorn
lethal smelt
cosmic dagger
sharp jolt
#

oh i found the fix... i had the same code underneath that i forgot to delete before i left to do something else...

cold mist
#

morning, is there any way i can get this bool in C#?

#

i want to deactivate a gameobject in the script

forest orbit
#

how can I clone this asset and put it in the same folder?

polar acorn
forest orbit
#

the characters folder

polar acorn
#

You're not gonna be putting anything in any folder at runtime

forest orbit
#

oh

#

thought you could do that

#

how can I loop through the children of this object?

cosmic dagger
slender nymph
#

you're better off just putting those objects into a list, but you could technically just foreach over the transform

forest orbit
#

its so over complicated for no reason jesus christ

slender nymph
#

it's really not

forest orbit
#

I wish I could just reference the object and do like foreach object in object:getchildren or something

slender nymph
#

since you're clearly ignoring everything that everyone is telling you and refusing to bother googling it, why are you even here?

polar acorn
#

The thing you wish it did instead is longer than the actual solution

forest orbit
#

perhaps im not smart enough for unity

lethal smelt
#
{
Something(child.gameObject)
}```
its litterly this easy
slender nymph
# forest orbit did google it

considering you think it is incredibly difficult to do this, i sincerely doubt you actually put any effort into reading the information returned by any google search

forest orbit
#

how do I get gameobject tho

polar acorn
forest orbit
#

do I have to manually drag an object into the component every single time

polar acorn
#

or by running this code on the object you want to use

polar acorn
#

it can't just divine that knowledge from the Spirit Realm

#

you gotta tell it

forest orbit
#

yea thats where I misunderstood

#

would be simpler if you could just reference any object that is in the scene

#

like in some other engines

lethal smelt
#

you can

#

just use Find

slender nymph
# forest orbit yea thats where I misunderstood

then you should start by learning the absolute basics of how c# and unity work. there are beginner c# courses pinned in this channel and the pathways on the unity !learn site are a good next step after you understand the fundamentals of the language

eternal falconBOT
#

:teacher: Unity Learn ↗

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

polar acorn
#

by dragging it in

#

that's how that works

forest orbit
slender nymph
#

learn the basics of c#

polar acorn
# forest orbit 😔

Neither Image or Canvas is a transform, and you can't just windmill slam a foreach loop in the middle of your class scope and expect it to work

cosmic dagger
slender nymph
#

also we went over this yesterday, you can't just have arbitrary code outside of a method

forest orbit
peak holly
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

forest orbit
#

isnt transform just position and rotation related?

peak holly
slender nymph
polar acorn
#

That's a different thing

forest orbit
polar acorn
forest orbit
#

parent* I mean

cosmic dagger
polar acorn
#

Mabye you should see if there's a function that can get a specific set of components in an object's children

forest orbit
#

If I were to assign a button to a variable, I'd type public Button blabla; so I just assumed that the different objects like button and canvas were the type

wintry quarry
wintry quarry
wanton epoch
#

I could use someones help with this issue I am having when turning my game into a multiplayer one.

My game a is 3d virtual art gallery and I use 2 gameobjects to determine the players camera/orientation/etc. Basically they communicate with each other to al;low the player to turn and move and see everything. The problem, is that I am using photon to make my game multiplayer, and I need to turn my player into a prefab and the gameobjects can no longer have the right reference needed.

For example, my CameraHOlder using a gameobject in my avatar called CameraPosition, but I dont know how to put the reference needed since im turning my avatar into a prefab.

wintry quarry
#

note that you should really oinly have one camera anyway per client

#

So if you go with 2. you would destroy or disable any camera except the local player's

wanton epoch
wintry quarry
#

I don't know how your camera holder works

#

if that will work or not

forest orbit
wintry quarry
#

it's an option but you might have to have it deparent itself when it spawns

wintry quarry
wintry quarry
#

because the child/parent relationship is defined in the Transform

wintry quarry
forest orbit
#

I see

#

so if I wanted to loop through the children of CharacterSelection I'd have to use CharacterSelection.GetChild(index)

slender nymph
#

assuming CharacterSelection was a variable of type Transform then yes, that is one way to loop through the children of that object

wintry quarry
forest orbit
#

trying to add this so I can drag it but everything just turns red

#

not even doing anything with it its just there

polar acorn
#

And the compiler has just given up

forest orbit
#

it works fine when I remove that one line public Transform lalala

polar acorn
modest dust
#

How do you expect to make a program if you have no idea whatsoever how to use the language required

#

None of this would be an issue if you spent some time on learning tha absolute basics

forest orbit
polar acorn
#

Protip: This line is the problem

forest orbit
#

what im asking is why that line would cause a problem, because all I'm doing is declaring that variable??

polar acorn
#

You cannot use access modifiers inside of a function

slender nymph
eternal needle
#

notlikethis how did you decide it'd also be a good idea to do multiplayer..

polar acorn
forest orbit
#

just have to do it

eternal needle
#

🤷‍♂️ you dont even have the fundamentals of c# down. How do you expect to do anything in unity, which uses c#

polar acorn
#

Perhaps if you spent as much time reading the documentation as you've spent wasting everyone's time on Discord you'd be done by now

slender nymph
#

or instead of lashing out and making a shitty attempt at insulting the people helping you like a whiny toddler, you could try learning the fundamentals

forest orbit
#

all I did was declaring a variable inside a function rather than inside the base class, not that big of a problem, I dont understand why you could just tell me that from the beginning

polar acorn
forest orbit
#

I dont understand why you have to be so pretentious, I just declared it inside of a function which apparently doesnt work in c#, at least not when its a public variable, you couldve just told me that instead of displaying your superiority

polar acorn
#

You've exceeded your patience quota for the day, but we have plenty of spite available

forest orbit
#

I'll let you get back to whatever you were doing then, I'm sorry if I'm having trouble figuring out the syntax

chrome apex
#

Why doesn't this work but only the first time around:

       if (int.Parse(name)>int.Parse(Winlevel.levelsPassed) + 1)
    {
        button.interactable = false;
    }
#

when I save it after completing a level into player prefs, it works

#

it gives me an error at the parse, which should be impossible

polar acorn
cosmic dagger
#

Try using TryParse instead . . .

slender nymph
wintry quarry
chrome apex
#

I get very strange results

#

for the second variable, it just says (object)

polar acorn
#

An empty string is not an int

chrome apex
#

ahhhh I know why it happens

#

cause it's getting the value from the playerprefs

#

so it doesn't work unless I save

#

i.e. pass a level first

#

so can I do if null, then value is 0?

polar acorn
#

You should consider TryParse instead

#

and if it fails to parse, set it to 0

slender nymph
#

why are you saving an integer as a string in PlayerPrefs?

polar acorn
#

You know what good call

chrome apex
chrome apex
#

trying to figure out which ones are locked, which unlocked

#

when for example level 3 is passed, the levelspassed variable is set to 3

slender nymph
#

so again, why are you saving an integer as a string in PlayerPrefs

chrome apex
#

then for all the other levels, int parse, if higher than 3, disable button for the level

#

I am saving a string, what

slender nymph
#

you already have it as an int, and you have the option to store an int in PlayerPrefs

#

so why are you instead saving it as a string

chrome apex
#

!code

eternal falconBOT
chrome apex
#
 if (int.Parse(SceneManager.GetActiveScene().name) > (int.Parse(levelsPassed)))
            {
            levelsPassed = SceneManager.GetActiveScene().name;
            PlayerPrefs.SetString("levelsComplete", levelsPassed);
            }
slender nymph
#

right so you have an int that you could use, but choose to use a string instead

chrome apex
#

ah yeah ok you have a point

cosmic dagger
chrome apex
#

I explained it above

cosmic dagger
#

Ok, don't mind me then . . .

chrome apex
#

ok so how do I handle that first load where there's nothing in the player prefs? Add a bool called hasData = false.

If !hasData, then levelspassed = 0
else load levelspassed fomr playerprefs.

I would flip the bool once the first level is completed.

Does that sound about right?

polar acorn
#

Just store the last level completed in an int

#

if it's 0, then you've beaten none

#

if it's 1, you've beaten 1

#

and so on

chrome apex
#

but on awake the menu scene loads that variable from playerprefs

polar acorn
chrome apex
#

when I just start the game, it errors

#

because it's null

slender nymph
#

what is the error

chrome apex
#

I mean, not error, it's an empty key from playerprefs

#

I only save it when I pass the first level

polar acorn
#

So you know what can't be empty string? An int

chrome apex
slender nymph
#

nor can int be null

chrome apex
#

that would work then

#

yes yes good solution

#

it being 0 by default works in my case

#

thanks

polar acorn
slender nymph
#

even if there wasn't somehow a default, you can specify a default if the key does not exist

chrome apex
#

still have to parse the name of the level into an int so it's the same amount of work

polar acorn
chrome apex
#

not that I'm not listening to you guys, I'm just trying to use my brain too

polar acorn
chrome apex
#

I didn't think about that other thing

polar acorn
#

Parsing one object is less than parsing two objects

slender nymph
#

you could also design your systems to not rely on the scene name and instead use some object in the scene or its build index or something

chrome apex
#

I'll listen to you and make the playerprefs var an int

wanton epoch
#

Has anyone had this issue before where, while using Photon, the person who creates the room can move around and turn their camera but anyone who joins the room is stuck in place and cant turn their camera?

wintry quarry
wanton epoch
#

alright thanks

honest haven
#

Im setting up joystick and for some reason GetButtonDown wont work but GetButton does - what am i doing wrong

slender nymph
#

provide more context such as !code

eternal falconBOT
honest haven
slender nymph
#

that is not a helpful amount of code

honest haven
wintry quarry
honest haven
#

heres my toggle class

#

no update

#

maybe thats where im going wrong - didnt think it was physics thought fixed up date was more for that

slender nymph
#

that is a single method, not a class. and not even where you are calling GetButtonDown

wintry quarry
#

no

#

fixedupdate would be bad

#

Input needs to be processed in Update

honest haven
#

yh its in update

wintry quarry
#

You seem to only be doing UpdateMenuStats in the first poart

#

not in the else

#

I'm assuming that's what modifies menuStatus?

#

oh nvm

honest haven
#

yh so menuState resets each time

chrome apex
#

it works now, thanks guys

honest haven
#

menuStatus

wintry quarry
honest haven
#

Using getbutton does it every frame and i get this

#

I am also using the old input manager

#

if that helps

wintry quarry
#

yeah exactly