#💻┃code-beginner

1 messages · Page 535 of 1

teal viper
#

Depends. But you definitely shouldn't put all your project's code in one file

modest dust
#

Define "everything"

foggy crypt
# modest dust Define "everything"

I mean I can define other game objects that I need via [SerializeField] and stuff, so I Don't even need to make different scripts for "Game Manager" or whatever

swift crag
#

Your question is a bit weird

teal viper
swift crag
#

Serialization lets you tell one object about another object

#

so that when the game runs, the first object can find the second object

modest dust
#

[SerializeField] only exposes a field to the inspector so that you can drag and drop it, it has nothing to do with defining other logic in the same file/class

foggy crypt
swift crag
#

Your conclusion doesn't make any sense to me

foggy crypt
#

🤩

alpine fjord
#

If you have 10 scripts with 100 lines each, it's easier to find something than if you had 1 script of 1000 lines.

swift crag
#
public class Enemy : MonoBehaviour {
  [SerializeField] List<Weapon> weapons;
}

public class Weapon : MonoBehaviour {
  public void Shoot() {

  }
}
#

I don't see how giving an Enemy a list of Weapon means that you no longer need the Weapon class!

#

(that seems self-defeating..)

teal viper
teal viper
foggy crypt
#

Yeah, I guess my project is just too simple for multiple scripts.
but it has 250 lines already idk

teal viper
foggy crypt
#

Yeah, like
Everything has it's name and number most of the time

swift crag
#

I'm very confused by what you're proposing here

teal viper
swift crag
#

you wouldn't do this

alpine fjord
swift crag
#
public class Game : MonoBehaviour {
  // The entire game
}
swift crag
#

A lot of the criticisms of that game are completely bogus

#

but the game is also still bogus

foggy crypt
polar acorn
swift crag
#

I can't watch those "yandere sim code sucks!!!" videos because they immediately make several dozen technical blunders

swift crag
#

Maybe I should elaborate on this

foggy crypt
polar acorn
swift crag
#

I am working on a game that is a lot like Alien Isolation.

polar acorn
swift crag
#

In the beginning, I had two absolutely enormous script files:

  • Player
  • Monster
teal viper
polar acorn
#

Do you want an all-in-one toothbrush, spatula, toilet brush, shaving razor, and rice cooker?

swift crag
#

The script files were way too big to deal with, and they made lots of assumptions about how the player and monster should work

foggy crypt
polar acorn
swift crag
#

If I want the monster to be able to do something, I add a little module that adds that feature

#

the player and the monster can share lots of logic (walking, seeing, hearing)

teal viper
swift crag
#

and also not share things (murdering the player)

swift crag
#

it's a very big book

foggy crypt
#

🤔

polar acorn
#

You want your scripts to be as single-purpose as possible. If you have a script for ducks and you want to change the rate at which ducks quack, you go to that specific script and change that specific thing. Rather than going on an archaeological dig through your monolithic Thing class that every single script uses and now you've also affected the rate at which trucks honk, guns reload, and enemies call for backup

swift crag
#

it would be a nightmare to read, because it'd be enormous -- and editing the book would require a lot of work

foggy crypt
swift crag
polar acorn
swift crag
#

now you have to renumber the entire book (which is the entire library)

#

and god help you if page 3496 says "see page 97455 for more details!"

polar acorn
#

You know I think the best way to answer this question is to just let you do it

swift crag
#

We're bumping into a big concept in "object oriented programming"

polar acorn
#

Go ahead

#

Try

swift crag
#

Encapsulation

foggy crypt
modest dust
#

One way to find out is to try and make a slightly bigger project.
Go ahead and try doing everything in a single file, you'll soon know why it's a bad idea

teal viper
# foggy crypt huh

You'll understand when you face a complex enough project. If it works for you now, just keep it as you like.

polar acorn
#

You've obviously decided you know more about it and won't heed any warnings anyway

#

So go ahead and try it

swift crag
#

yeah, I think you just need to try it and see, haha

#

But perhaps I can give one more example to convince you

swift crag
modest dust
#

If words aren't enough then practice will teach you

swift crag
#

you have different numbers of different things

foggy crypt
swift crag
#

If your Character class also deals with cameras and with managing the game, it'll be a complete nightmare to add a second Character

#

coming back to my game: an Entity can be many things:

  • The player
  • The monster
  • A lever
#

therefore, I only put things in Entity that every Entity must have. Everything else goes into other components.

foggy crypt
swift crag
polar acorn
foggy crypt
#

Well, multiplayer yeah
But I think it's a different story

polar acorn
#

I might need to be thawed out by the time you finish though

foggy crypt
swift crag
#

manually rendering everything

teal viper
swift crag
#

we don't need no stinkin' Renderers!

teal viper
#

It's not really something you can call an experience

foggy crypt
#

Okay 6 hours

eternal needle
teal viper
foggy crypt
#

And still, it's not my first project after all
And I did everything in 1 script before as well

modest dust
#

And how much prior programming knowledge do you have?

foggy crypt
#

so whatever

alpine fjord
#

Just give up.

eternal needle
# foggy crypt Well I certainly didn't do that 🙂 I'm just saying that a month can be a month

you can code for a year, if you're making bad code then all you've learned is bad code. ive skimmed through the chat above and it really seems like you're nit picking these comparisions (like library/book) instead of just accepting the answer. Theres literally no reason to make all your game in 1 script. If you wanna do it, go ahead and learn the downsides when you come across them. Or when you try to show off this project and become the next yandere dev of the community if you get that far

timber tide
#

Dont give up.

teal viper
foggy crypt
alpine fjord
foggy crypt
alpine fjord
teal viper
# foggy crypt Why did you expect experience in <#497874004401586176> lol

Here's a simple analogy that might help to understand a little bit better.
Imagine you rent an apartment, but that apartment has everything in 1 room: the kitchen, the bed, the toilet, the working space. Everything in one room. Now, imagine your toilet breaks and starts spitting shit all over. Your whole daily life would be ruined. If the toilet was in it's dedicated room, it wouldn't affect you as much.

foggy crypt
#

Why would you say that
I'm listening
I just don't have to accept your point of view like what
I'm thinking of big stuff that actual 3A games have
I think of the code that might actually be behind that stuff and it looks simple to me

foggy crypt
#

And my toiled didnt cough shit yet so whatever

#

Livable

teal viper
#

I have yet to see a toilet in the middle of a living room.

modest dust
#

Yeah, I feel like it's just best to let him experience it by himself

eternal needle
teal viper
# foggy crypt fr

Anyways, it feels like this conversation doesn't progress anywhere. And this is not a place for social chat. You can look at more complex projects online. Hopefully that would help you understand that your approach is really only feasible for very small and simple projects.

modest dust
#

The Unity courses as well as any programming courses are structured the way they are for a reason

#

Time will show what comes out of this

eternal needle
#

the first use case you'd see against this is that unity is already structured in a way where your code isnt in one script. There's already a transform, colliders, rigidbody. they exist as their own scripts. Why use unity if you want everything in 1 file?

foggy crypt
eternal needle
lusty cairn
#

Question: I'm trying to setup a system where when a player steps on a tile, it animates to a different tile. In game it will be a flower that dissapears when you step on it. I can't find anything online on how to use tile collisions as triggers for that, and im trying to figure out if anyone knows or if I should scrap it

wintry quarry
lusty cairn
#

explain it to me like I am a narrative designer that just got put on programming bc our programmer swapped to music and Idk what I'm doing hahha 🙏

latent tinsel
#

I am watching this tutorial and the guy on his screen has the keywords showing for him and I do not. How do I get the keywords like him?

eternal falconBOT
nocturne kayak
#

correct me if i'm wrong, but an interface is a collection of variables and methods, right?

rich adder
#

not really

hardy maple
wintry quarry
nocturne kayak
rich adder
#

thats why they are thought as "a contract " , because they have obligation to implement those methods in the class/struct

nocturne kayak
#

In that case, why would i use an interface over just writting that logic per class?

#

It's not that i'm doubting the usefulness of interfaces, i'm genuinely trying to understand the use cases

rich adder
#

mostly to have a common method/properties some classes/structs share
and you are ensuring you will always find those methods in those classes

timber tide
#

Interfaces are surprisingly extra useful with unity

#

or game dev in general

nocturne kayak
#

oh boy

rich adder
#

they are comparible to abstract methods but they don't need to be in a parent class to inherit from, a class/struct can have multiple interfaces

hollow obsidian
#

is there an updated tutorial for the new input system? In junior programmer pathway unity used the old system want now learn how the new one works

hardy maple
#

Heres an example. You might have an interface called IWheeled which says that there must be a method called SpinWheels.

Then you could have a Car class that extends IWheeled and a motorcycle class that extends IWheeled.

Then you could have some process that goes through all the Classes that extend IWheeled and calls SpinWheels. This class doesn't know or care if it's dealing with a Car or a Motorcycle it just knows that whatever it's dealing with has promised to have a SpinWheels method

teal viper
hollow obsidian
rich adder
wintry quarry
hollow obsidian
#

ok

nocturne kayak
#

Can i have an interface inherit from another?

wintry quarry
#

or even just code that raycasts and finds any interactable component on an object and interacts with it

#

that's a very common use case

hardy maple
hardy maple
nocturne kayak
#

Alright, my eyes have been opened to the magic of telling a bunch of scripts what to do

hollow obsidian
# rich adder https://docs.unity3d.com/Packages/com.unity.inputsystem@1.11/manual/QuickStartGu...

ah ok thats interested thanks. so this way i used is not the right way?

using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    private Rigidbody rb;
    private float movementX;
    private float movementY;
    public float speed;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void OnMove(InputValue movementValue)
    {
        Vector2 movementVector = movementValue.Get<Vector2>();
        movementX = movementVector.x;
        movementY = movementVector.y;
    }

    private void FixedUpdate()
    {
        Vector3 movement = new Vector3(movementX, 0.0f, movementY);
        rb.AddForce(movement * speed);    
    }
}
rich adder
#

you could just store movement as a v2 btw

timber tide
# nocturne kayak Alright, my eyes have been opened to the magic of telling a bunch of scripts wha...
public interface IDamageable
{
    int Health { get; set; }
}

public class Enemy : MonoBehaviour, IDamageable
{
    public int Health { get; set; }
}

public class Player : MonoBehaviour, IDamageable
{
    public int Health { get; set; }
}

public class Projectile : MonoBehaviour
{
    int damage = 10;

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.TryGetComponent<IDamageable>(out IDamageable damageable))
        {
            damageable.Health -= damage;
        }
    }
}```

Here you don't give a crap what type it is and only the interface... so overall you're doing less comparisons. Another thing about interfaces is you can pass object references around by their interfaces only and exposing only what properties those interfaces include.
#

And, health here can be implemented completely different between the two

wintry quarry
#

^ one of my favorite things to do is pass Lists around as an IReadOnlyList

timber tide
#

Say, you only want player to only ever take 1 damage regardless

nocturne kayak
#

that's something else i've kinda been ignoring

#

why the { get; set;} specification?

hardy maple
#

Does that work with Dictionaries?

timber tide
# nocturne kayak why the { get; set;} specification?

That's just a property field which you still need to implement, so for instance on player you want something like this. Properties are just mini-methods after all

private int health;
public int Health
{
    get => health; 
    set
    {
        health = Mathf.Clamp(value, 0, MaxHealth);
        if (health <= 0)
        {
            Die();
        }
    }
 }
hardy maple
wintry quarry
timber tide
#

Instead you could just implement two methods like

public interface IDamageable
{
  public void SetHealth(int health);
  public int GetHealth();
}

Instead

nocturne kayak
wintry quarry
#

(on the interface)

#

on the classes it's setting up the auto-implemented property

#

I never thought about the fact that it's doing a slightly different thing for an interface!

steep rose
#

this is going off the notion that damage never changes

timber tide
#

It would pass in the same parameter, yes. But you can have different implementations on both enemy and player

#

So like think of a game where you only want the player to take 1 damage only ever, but enemies can get 1+ damage like in zelda

#

^ well depends on the zelda game but some other retro games did similar

#

Or, maybe in the property implementation of player they also call InvulFrames(); because they get a few frames of invulnerability (enemies dont)

steep rose
latent tinsel
#

Hello, does anyone know what IDE stand for?

wintry quarry
steep rose
#

Integrated development environment

rich adder
wintry quarry
#

but you could have googled that...

north scroll
#

Hai I'm having issues with a drop down menu. On my player.cs script, I have a function:

Public void DropdownMenu(int index)
{
Switch(index)
{
Case 0: playerStatus = PlayerStatus.walking
Debug.log(playerStatus);
Break;
Case 1: playerStatus = PlayerStatus.shooting
Debug.log(playerStatus);
Break;

    }

}

I have this script attached to a player prefab since it's instantianted. On the ui drop down menu, under the "ON VALUE CHANGED", I have that prefab's script with the Player.DropdownMenu function on it, and the proper index for each. But when I run the game, and click on each drop down, it looks like the console prints out both Switch statements for index 0 and 1, so it's like the Break is not working for some reason. Also, I can see the index cha going on the actual drop down item in the inspector

eternal falconBOT
north scroll
#

I'm on mooobile

steep rose
#

you can google on a phone

north scroll
#

What

steep rose
#

oops

rich adder
wintry quarry
timber tide
steep rose
latent tinsel
rich adder
north scroll
#

Sry yall I'm hoping it's clear enough

#

There's 3 actually, but the issue is the same, all 3 run on the console for some reason

wintry quarry
#

every time you change the dropdown, it's going to call it 3 times

#

once with each of those values

north scroll
#

Oh I thought it would run the function with that index in mind

wintry quarry
#

You need to remove all three of those, and add the function again

#

but this time from the dynamic parameters list

#

not from the static parameters list

#

And just FYI - life is easier when you use discord on your PC

north scroll
#

What's the dynamic parameters list? The value up above that picture ?

#

I know I'm at my job rn waiting till 1030 then I can access wifi again

wintry quarry
#

See where it says Dynamic int

#

instead of Static Parameters

#

trying again lol

latent glade
#
    {
        if (inputs.FindAction("Escape").ReadValue<float>() == 1)
        {
            if (!pauseMenu.activeSelf == true)
            {
                Time.timeScale = 0f;
                //Freezes time ingame
                pauseMenu.SetActive(true);
                Cursor.visible = true;
                Debug.Log("Esc activating pause menu");
            }
            else {
                resume();
                Debug.Log("Esc Deactivating pause menu");
            }
            Debug.Log("Esc has been tapped");
        }
    }```
for some reason, the menu only appears if it isn't there. When I hit escape, it also only debugs "esc has been tapped" when it activates the pausemenu and also says "Esc activating pause menu".
steep rose
north scroll
# wintry quarry trying again lol

I see dynamic int bit it's grayed out when I put the player.cs (per the prefab) on it... and without it the "no function" doesn't let me click on anything

latent glade
#

void resume is:

    {
        Time.timeScale = 1.0f;
        pauseMenu.SetActive(false);
        Cursor.visible = false;
    }```
wintry quarry
latent glade
#

does timescale not affect update

wintry quarry
#

no

#

timescale doens't affect update

#

Update runs every frame no matter what

teal viper
wintry quarry
#

alsocs inputs.FindAction("Escape").ReadValue<float>() == 1 this is not the way to check for a button press

#

You want cs inputs.FindAction("Escape").WasPressedThisFrame(), which will work reliably when you handle input in Upate

timber tide
steep rose
wintry quarry
latent glade
#

alright it works ty guys

#

likely the timing

north scroll
#

aight using hotspot then, @wintry quarry

wintry quarry
#

It's right there

#

Working fine

north scroll
#

yea i said i couldnt click on it cuz its grayed out

#

ohhh

#

i get it

wintry quarry
#

Click your function name

north scroll
#

its not a thing to click

wintry quarry
#

yeah it's just a section header

north scroll
#

its a title or whayever, gotchu

#

tyy

nocturne kayak
#

Alright, so

#

i made an interface

#

i implemented that interface in something

#

now, how do i tell a ray to look for something that implements said interface?

teal viper
final sluice
#

So here is my code
I haven't used getcomponent to refer to the script inside m_gc to use its IncrementScore function. How come I can still use it if I just use FindFIrstObjectByType ?

timber tide
#

You specify the component when you searched for it

final sluice
timber tide
#

Not that I would consider using this method, but you did a search by the component itself. It's not like you've got a GameObject returned instead, and if you did then you'd probably want to use GetComponent to find the GameController on it.

wintry quarry
#

that's why you can call IncrementScore on m_gc

polar acorn
wintry quarry
#

FindFirstObjectByType is actually completely irrelevant to why you can call the function on m_gc

#

That is how you assigned the variable

#

but it's not why you can access the members of the GameController type

final sluice
#

I always thought you have to find the object first to find the component inside it.

polar acorn
#

You could eliminate the Find entirely and it'd still compile. You'd get a Null Reference Exception, but that'd be perfectly cromulent code

wintry quarry
#

You don't have to Find anything ever

#

GetComponent gets you a component from a GameObject but there's no rule you have to start with a GameObject reference.

timber tide
#

Majority of the time you'll be using GetComponent when doing some raycast query or through physics and collision contacts

#

as most of this stuff can be serialized on the editor or some other explicit way

final sluice
#

This is my code for the Ball gameobject
I tested the collision in and out of the if loop and I find no collision at all when they hit the platform(player) (Check the console for Debug.log lines but I find nothing ). What might be the reason for this ?

wintry quarry
final sluice
#

ok never mind I foudn the problem. I forgot to add the script into the ball gameobeject -_-

wintry quarry
#

That'll do it

nocturne kayak
#

Let's say i have an ISelectable Interface, if i get a reference to that interface then do, let's say, iSelectableReference.Disselect();

#

is it going to perform that method on every single script implementing that interface?

slender nymph
#

no, it would only call that method on the instance you have referenced

wintry quarry
#

someReference.Something() always just calls Something on the particular reference you have there

#

that's what the reference is for

nocturne kayak
#

Alright, this is weird

#

This code is giving me an Use of unassigned local variable on line 70

#

even though i believe i'm setting said variable on like 59

wintry quarry
nocturne kayak
#

o h .

wintry quarry
#

So it's possible it's not assigned there

nocturne kayak
#

i tried adding a && selectableFurniture != null on the following if statements

#

but that didn't seem to solve it

#

if i'm checking if a variable isn't null beforehand, shouldn't that solve it?

slender nymph
#

you can assign null to it on the line you declare it if you want to keep this structure. otherwise consider restructuring this code so that these lines are only running if that variable is assigned

#

also since it is a local variable, it can never be anything other than unassigned or null in that last else if you have

wintry quarry
#

You need to store the object in a member variable so you can access it next frame

nocturne kayak
#

yeah

#

that whole method's a mess

#

i'm still wondering how to improve it

wintry quarry
# nocturne kayak i'm still wondering how to improve it

When I've written code like this in the past I've structured it like:

Target oldTarget;

void Update() {
  Target target = null;
  if (Physics.Raycast(..., out HitInfo hit) && hit.TryGetComponent(out target)) {
    // Something to do every frame while hovering the target here...
  }

  if (oldTarget != target) {
     if (oldTarget != null) oldTarget.OnLostFocus();
     if (target != null) target.OnGainedFocus();
  }

  oldTarget = target;
}```
#

Also:

rayOrigin.transform.TransformDirection(Vector3.forward)```
This can just be:
```cs
rayOrigin.forward;```
bright sequoia
#

Wondering if I could get some guidance; I'm trying to write it to where when my character's rb (2d) collides with triggers, that those trigger objects show a white outline (I have the material already and it works fine when I apply it manually). I then want the option to press E to show unique dialogue for each item

I was beginning to try using an interface for the interaction system, but before that, I cant get the outlines right. Last night I had it to where the outline was applied but didnt go away, and now its not even being applied at all haha, and cgpt is NOT helping. If anyone could give me some pointers, that would be awesome .I only started learning C# a couple weeks ago hence why I'm struggling with such a seemingly simple script. Not necessarily looking for someone to SOLVE this for me as I'm trying to learn, but i could use some pointers lol

This is my current player script that has both my player's movements and the non-working outline interaction system notcatpray

(https://paste.ofcode.org/PWZ629VNWABdnXr8FDbH2B)

(edited since text was longer than i expected)

wintry quarry
#

The main thing I notice off the bat is that this code will not properly handle the case of multiple overlapping colliders simultenously.

bright sequoia
wintry quarry
#

it's changing the material on your SpriteRenderer

#

Which will change how the player is rendered (based on those materials)

bright sequoia
#

I have a material from a shader that applies an outline called outlineMaterial; how would I apply that?

wintry quarry
#

And how is the shader intended to be used?

#

Most outline shaders I know of are for MeshRenderer and usually they are intended to be added as a second material (i.e. they render the object a second time, as an outline), not to replace the main material

bright sequoia
wintry quarry
#

was it a replacement, or did you add it as a second material?

bright sequoia
wintry quarry
#

btw that's equivalent to replacing the material on the SpriteRenderer

#

Ok so the next part here is you need to debug your code

#

make sure the part that changes the material is actually running

bright sequoia
wintry quarry
#

right now you should get the basic part working

bright sequoia
#

right
thank you :)

nocturne kayak
#

and well

#

i can't get to the unHovered state now

#

and it's way too late for me to understand what i'm doing wrong

wintry quarry
#

it's way too late for me to understand
Why do you say that 🤔

nocturne kayak
#

like, it's 5 AM

#

the old synapser is fried at this point

wintry quarry
#

Then go to sleep and revisit it tomorrow

nocturne kayak
#

i tried redoing this three different ways and no shot in the past two hours

wintry quarry
#

but uh

#

you're using the wrong variable on lines 98-109

nocturne kayak
#

Is there any chance it's an obvious little silly mistake i'm making? because my guess is i'm never getting some shuteye before i fix this

wintry quarry
#

You should be using localSelectableFurniture and checkerSelectableFurniture, not selectableFurniture

naive pawn
wintry quarry
#
if (localSelectableFurniture != checkerSelectableFurniture)
{
    if (localSelectableFurniture != null)
    {
        Debug.Log("Stopped Hovering");
        localSelectableFurniture.onUnselected();
    }
    if (checkerSelectableFurniture != null)
    {
        Debug.Log("Hovering");
        checkerSelectableFurniture.onHovered();
    }
}``` This not what you've got
#

those variable names are 😵‍💫 though

#

especially at 5am

nocturne kayak
#

that works

#

and it makes sense

#

and it's so obvious

#

@naive pawn is right

#

i probably should've gone to sleep three hours ago

pliant abyss
#

oaidjhf;laqkjf;liarf;lkaJF;LAdf;ljDFA;LJKADKJFL

Translation: often the act of typing out and checking your details is what lets you solve a problem, even as you are in the middle of reaching out for help. I fixed this after 3 hours. So obvious. @nocturne kayak right there with you.

naive pawn
#

ah, the ol' rubber duck method

#

(why are you in caecpr's bed)

pliant abyss
naive pawn
#

explain your code to a rubber duck

#

it's a debugging method

#

it forces you to slow down and go step-by-step

#

that's what asking a (good) question here also does

pliant abyss
# naive pawn (why are you in caecpr's bed)

I have class called Pathwinder I am using for pathfinding. I have a parent GameObject of a ship for a twin-stick shooter, and an abstract class called HelperShip. I have two helper ships who follow distinct paths in formation near the parent ship. One was working as expected, the other was not.

In the end: my prefabs were configured incorrectly. Pop the information into the prefab, boom. It works.

whole ridge
#

Hey guys, I'm a little bit confused by Cinemachine in Unity 6. It seems to have had a large update. What would be the best way to add camera sway now?

umbral sun
#
 {

     //     [SerializeField] int[] numeroTaulukko = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };

     for (int i = 0; i < numeroTaulukko.Length; i++)
     {
        if ( numeroTaulukko[i] == original)
         {
             numeroTaulukko[i] = replacement;
         }
     }
 }

how can i make script to replace all 5 with -1

whole ridge
#

Where is the problem with your current script?

languid spire
frail hawk
#

change it to int[] and return the numeroTaulukko at the end, it shoudl work

night raptor
languid spire
#

logically you would return bool to indicate one or more replacements have been made or int to show the number of replacements made or void

frail hawk
#

well he never told us what he really is trying to do so i assumed

night raptor
#

oh yeah, number of replacements makes sense

rain ginkgo
#

while generating runtime navmesh surface, everytime it lags a lot, what can I do to reduce lag?
I have optimized the voxel and tile size to the maximum possible amount

teal viper
rain ginkgo
#

right now it just generates a volume around the player every time it moves a few chunks

teal viper
rain ginkgo
#

unity 6

teal viper
rain ginkgo
#

ah, im not aware of that, i just followed a tutorial.

teal viper
#

That should run async(probably on a back thread) and not stall the main thread.

#

Well, if you want to use up to date api, you'll need to read the documentation. There's not gonna be a tutorial on everything.

crisp eagle
#

Code runs once(incorrently) and then throws a "NullReferenceException: Object reference not set to an instance of an object"

    {
    skipper = !skipper;
    
    if (skipper == false)
    {
        reportsGO[index].SetActive(true);
        reports[index].UpdateStats();
        index++;
    }
}```
onPrimaryButtonEvent has no issue and works fine until I add the updatestats line.

updatestats is in another script, assigned to a group of objects which are accessed by the index.

```    public void UpdateStats()
    {
        S.text = Convert.ToString(patient.eyeStats.x);
        C.text = Convert.ToString(patient.eyeStats.y);
    }

S and C are TMPtext

naive pawn
#

where does the stacktrace point to?

hexed terrace
#

The console tells you which line has the null reference... don't make us guess

ivory bobcat
crisp eagle
#

This is hard to explain

hexed terrace
#

It's not hard to explain

#

what code is on line 80 in Autorecfractometer.cs ?

crisp eagle
#

It points to this code:

{
    bool tempState = false;
    foreach (var device in devicesWithPrimaryButton)
    {
        bool primaryButtonState = false;
        tempState = device.TryGetFeatureValue(CommonUsages.primary2DAxisClick, out primaryButtonState) // did get a value, also it used to be "primaryButton"
                    && primaryButtonState // the value we got
                    || tempState; // cumulative result from other controllers
    }

    if (tempState != lastButtonState) // Button state changed since last frame
    {
        primaryButtonPress.Invoke(tempState);///////////////////////////////////////////
        lastButtonState = tempState;
    }
}```
#

On the line I added the //////// in

hexed terrace
#

No it doesn't

rain ginkgo
crisp eagle
hexed terrace
#

reports or the element at index is empty, it hasn't been assigned - or the object has been destroyed

crisp eagle
teal viper
hexed terrace
#

the computer knows better than you 😉

crisp eagle
#

not runtime

teal viper
#

Always confirm the setup at runtime.

crisp eagle
#

hold on lemme check

languid spire
#

Debug your code so instead of assuming you will know

crisp eagle
#

it turns to none for some reason at runtime?

#

ok thank I think I found the issue

naive pawn
#

then find where you're doing that

crisp eagle
#

Sorry for being annoying, thanks again

queen adder
#

Yo im completely new to unity and know nothing abt coding. I just finished the 2d tutorial template yesterday, was wondering if it’s a good idea to just copy and paste the demo’s script, but tweak it a bit to my liking?

teal viper
queen adder
#

Bet

teal viper
#

Though, you might not ever get used to writing your own code from scratch like that.

#

It's a transition issue that some people have.

queen adder
#

Do you think it’s a good starting point tho, because I do want to eventually learn it

#

What’s ur “meta” for learning stuff like this

#

Rn my goal is to make a game with very basic mechanics like fancy pants or like the old flash games

queen adder
#

Awesome, ty🙏

crisp eagle
#

but the scripts I am targeting are part of a prefab

#

could that cause the issue?

languid spire
#

yes, you are probably using a reference to the prefab rather than the instantiated gameobject

crisp eagle
#

reports[index].GetComponent<Report>().UpdateStats();

#

Works now

fickle skiff
#

How might one create a 2d character controller in Unity 6?

#

(im new to Unity and coding as a whole)

hexed terrace
eternal falconBOT
#

:teacher: Unity Learn ↗

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

final sluice
#

I create a text slot in my UIManager to put in the text "ScoreText" component , but I can't, what is the reason for this ?

hexed terrace
#

Text is legacy and shouldn't be used any more

#

declare the var type as TMP_Text

final sluice
#

It works now , thank you

hollow obsidian
#

is that normal closing takes time?

hexed terrace
rain ginkgo
teal viper
eternal falconBOT
#

:teacher: Unity Learn ↗

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

somber nimbus
#

Hello! I have this coin collection script, but I have to make it so that the coins are saved and can be used throughout the game. I found the playerprefs system but I don't understand it very well, could someone explain to me how would I use it with this script?

swift crag
#

PlayerPrefs lets you read and write simple values (numbers and strings). The values don't go away when you restart the game.

#

There are some examples in the documentation.

#

If you just want to remember a value within a single game session, consider using a static field.

public static class PlayerData {
  public static int coins;
}

Could be as simple as that.

#
PlayerData.coins += 10;
#

This will reset every time the game starts (as does basically everything else!)

somber nimbus
#

Ooh, I see :0

#

Thank you so much! Will read the docs

swift crag
#

static means that the field is not part of a specific object

#

it's attached to the class itself

somber nimbus
#

Okay

swift crag
#

static class just ensures that everything in the class is static

#

it's not necessary

somber nimbus
#

Got it :)

burnt vapor
eternal falconBOT
somber nimbus
#

But really, thanks! I was so stuck on that

burnt vapor
#

Also useful for @swift crag to point people to configure it when you see this

swift crag
#

I don't see anything obviously wrong in the screenshot

somber nimbus
frail hawk
#

intellisense is missing

swift crag
#

Is it missing some syntax highlighting?

#

Ah

somber nimbus
#

And it has autocompletion enabled and stuff

somber nimbus
burnt vapor
#

You seem to be missing syntax highlighting, which means you probably also miss out on editor warnings and such

swift crag
#

If it says "Miscellaneous files" in the top left instead of "Assembly-CSharp", it's busted

fleet onyx
#

Hello, I just updated unity from 6000.0.24f1 to 6000.0.29f1. When opening the project, unity asked me to enter safe mode. Then, I saw errors in console, it said that strings like TMPro, UI does not exist (??) but I didn't change anything?

somber nimbus
#

It happened yesterday but I just left it that way and have been working with that so far

swift crag
burnt vapor
#

I suggest you follow the steps listed if restarting does not help

swift crag
#

If it's still messed up, go to Preferences > External Tools and regenerate the project files, then restart the IDE

#

and if it's still borked, then yeah, follow the steps from the bot message

#

Rider randomly throws up and completely breaks for me

burnt vapor
somber nimbus
fleet onyx
#

btw this error only occurs in the newest unity version, on the one I was using there are no issues

burnt vapor
#

It could be a lot of things. I'd assume it simply hasn't downloaded the DLLs now so removing the lib folder regenerates this

swift crag
#

I've seen this happen a couple of times. It's kind of mysterious

#

Sometimes Unity will be adamant that a specific assembly does not exist, even after nuking the Library

#

I've seen it be caused by corruption in the global package cache

burnt vapor
#

It could also be due to compiler errors but this is usually only related to DLLs from user code

#

I honestly think it's just drunk

#

Otherwise uninstalling/reinstalling TMP might help here. I have had to do this A LOT back in .NET Framework days even though it changed nothing

fleet onyx
#

nothing, still same issue. Maybe it could be a solution trying to install back again the editor?

fleet onyx
#

even reinstalling editor, won't fix issue

inland ridge
#

Hey, could somebody explain me what .isGrounded is exactly for the character controller? I have the following Code and I've run into some issues:

        bool isGrounded = _controler.isGrounded; 
        if (!isGrounded)
        {
            moveVelocity.y -= -moveVelocity.y + gravity * Time.deltaTime;
        }

As you can see, I've got an boolean isGrounded what is the same as the .isGrounded from the character controller.
However, this boolean is almost every time at false. The only time it is on true, is when I move the character (even if it is mid air).
Because of that the player could just fly by moving the character without falling, what shouldn't be possible, so how can I fix it?

naive pawn
#

why are you doing gravity manually instead of letting physics handle it?

#

that aside, you're subtracting a negative number, so that code is actually making you go up

hexed terrace
#

.isGrounded is pretty self explanatory ... it's a bool to tell you if the CC is grounded or not (ie: in the air). It sounds like you may not have it setup correctly - though I've never used the CC so don't know.

That bool declaration is also pointless, just do
if (!_controller.isGrounded)

naive pawn
#
moveVelocity.y = 2 * moveVelocity.y - gravity * Time.deltaTime;
```that statement is equivalent to this
#

so.. yeah that just doesn't make sense

naive pawn
#

if you were to implement gravity it'd be like this

moveVelocity.y += gravity * Time.deltaTime;
#

(but still, just do it with physics)

wintry quarry
#

Usign a CharacterController you don't get gravity automatically

#

it's not a Rigidbody

queen adder
#

How to acess the Cinemachine Target with code, to use it on a prefab? If i try to google it all i find is group target (Its a Camera 2D btw)

inland ridge
#

Thank you guys for your answers.

@naive pawn
Like @wintry quarry said, character controller doesn't get gravity automaticly, thats why I do it in Code. Also my current code does work, because I did -= -moveVelocity.y and thats why the character doesn't move up, but down.

@wintry quarry
Yes, I've read the documentation, and what I've got from that was that "If it is on ground, it sets the value to true" but it didn't do that. Thats why I've got confused.

However. My Problem stays the same. I still don't know why it is only true when I move the character, and not when I am on ground

wintry quarry
#

Read it again

#

very carefully

#

Was the CharacterController touching the ground during the last move

naive pawn
#

a rigidbody would handle gravity automatically, along with collisions with the ground or other objects

inland ridge
#

Because Character Controler and rigidbody doesn't work together. My character just glitches around then

naive pawn
#

ah.

#

anyways, your code works in the sense of going down, but not because of gravity. it works because you're doubling the velocity, and then adding gravity on top of that (which i suspect is positive as a serialized field instead of negative, then?)

inland ridge
naive pawn
#

doubling the velocity is not how acceleration works

inland ridge
#

My Problem is not that the gravity doesn't work btw. I just wanna now why my isGrounded boolean stays on false when it touches the ground, but goes on true when I move the character

#

I don't really care on how the acceleration works right now

gloomy lagoon
#

Hi I have a question about Visual Scripting.
How can I set number value of the component?

wintry quarry
inland ridge
#

Is anyone here now who can explain to me why the CharacterController.isGrounded stays at false even if my character is one ground and goes on true when I move the character midair or on ground? Or did you guys just wanna tell me the same things again

wintry quarry
inland ridge
#

Okay, so you wanna tell me that I understood it right in the first place, and it should work the way I do it, but its shitty and that's why the things I have are happening?

wintry quarry
#

Well the way it works is going to depend heavily on how the rest of your code is set up

#

it's just very finicky/sensitive

inland ridge
#

Okay, but why didn't you say that in the first place and just told to read the same sentence over and over again, when I have no way of getting that from this sentence 🤦‍♂️

wintry quarry
#

idk

#

general pedantry?

gaunt sandal
#

I am needing help:

I currently am trying to make a toggle that invert's the y-axis for looking around. I am saving whether the toggle is inverted or not in PlayerPrefs. For some reason, it saves when I toggle it on, but when I:

  • turn it off,
  • save,
  • go to a different scene,
  • then go back to the options scene that has the toggle, the toggle is on.

Anyone have any ideas why it refuses to turn off?

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class OptionsMenu : MonoBehaviour
{
    bool isOn;
    public Toggle invertToggle;
    // Start is called before the first frame update
    void Start()
    {
        PlayerPrefs.SetInt("InvertYAxis", 0);
        PlayerPrefs.Save();
    }
    void Awake()
    {
        if (!PlayerPrefs.HasKey("InvertYAxis"))
        {
            Debug.Log("Creating InvertYAxis");
            PlayerPrefs.SetInt("InvertYAxis", 0);
            PlayerPrefs.Save();
        }

        isOn = PlayerPrefs.GetInt("InvertYAxis") == 1;

        if (invertToggle != null)
        {
            invertToggle.isOn = isOn;
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void InvertYAxis()
    {
        isOn = !isOn;
        PlayerPrefs.SetInt("InvertYAxis", isOn ? 1: 0);
        Debug.Log("Toggling InvertedYAxis");
        Debug.Log("InvertYAxis: " + PlayerPrefs.GetInt("InvertYAxis"));
    }

    public void Apply()
    {
        Debug.Log("Saved Preferences!");
        PlayerPrefs.Save();
    }

    public void Back()
    {
        SceneManager.LoadScene("MainMenu");
    }
}
languid spire
#

it's pretty obvious, you are overwriting the pref in Start

polar acorn
#

Meaning every time you start the game, it's 0

wintry quarry
gaunt sandal
#

but that should forcibly turn it off, no?

#

i added that bit after i noticed this issue was occurring

wintry quarry
polar acorn
gaunt sandal
gaunt sandal
wintry quarry
#

you should be using invertToggle.SetValueWithoutNotify

#

the other problem you have is that instead of reading the actual bool value from the toggle, you're simply blindly inverting it

#

SO yeah that's what's happening

#

you're doing invertToggle.isOn = isOn; and that's calling the callback function, which inverts it again.

#

Two changes I would make:

  • Switch that to SetValueWithoutNotify
  • Make the callback function actually accept a bool parameter and use that, instead of blindly inverting the current value
#

The first change alone should fix things but doing both would be more robust in general.

gaunt sandal
#

So, I did try to make the callback take a bool before, but I couldn't figure out how to pass the toggle's state to the bool

wintry quarry
gaunt sandal
#

Thank yall for your help!

ancient junco
#

I am having a problem with checking if a key is pressed, I used Input.getkeydown and it only happens sometimes, and if i use Input.getkey it happens multiple times per key pressed. i think it is frame related?

swift crag
#

You don't want to use GetKeyDown inside of a physics callback

#

Those only get invoked 50 times per second (not once per frame)

#

You might completely miss the single frame where GetKeyDown returns true

naive pawn
#

OnTriggerStay is physics-bound, inputs are frame-bound.
you need to poll on frames

swift crag
#

Consider using GetKey and then setting a variable

#
if (Input.GetKey(KeyCode.Q) && !pressed)) {
  pressed = true;
}
#

you could reset pressed to false when the key isn't being pressed

naive pawn
#

(shouldn't it be GetKeyDown so it only triggers once)

ancient junco
#

ahh okay, thanks for the responses guys! that makes sense, i'll do this, or is it bad to be doing this in OnTriggerStay()? should it be in the update or somewhere instead?

swift crag
#

You could also use GetKeyDown in the Update method.

#

Perhaps you could do this

#
bool pressed = false;

void Update() {
  pressed = GetKeyDown(KeyCode.Q);
}

void OnTriggerStay(Collider other) {
  if (pressed && other.tag == "Whatever") {
    // ...
  }
}
#

Actually, no, this is wrong!

#

If two frames render before OnTriggerStay gets called, the input gets lost

#

this is actually just as bad as the original code lmao

swift crag
languid spire
#
bool pressed = false;

void Update() {
  if(GetKeyDown(KeyCode.Q)) pressed=true;
}

void OnTriggerStay(Collider other) {
  if (pressed && other.tag == "Whatever") {
    pressed = false;
    // ...
  }
}
swift crag
#

Yeah, that's what I should've written (:

#

Set it, then clear it later

cosmic quail
#

isnt it better to set a bool to true on trigger enter and set it to false on trigger exit and then in update check that bool and getkeydown together?

swift crag
#

It'd be roughly equivalent.

naive pawn
#

with your method, the physics tick rate is the constraint for the rate of action

#

doing it in update lets the framerate be the constraint

#

(cc @cosmic quail ^)

swift crag
#

well, 2 frames where the key goes down, but yeah -- it'll be more accurate at very high framerates

#

definitely an improvement

naive pawn
#

yeah, that's what i mean. kinda ambiguous 😅

long jacinth
#

bruh why is vs not working properly

polar acorn
eternal falconBOT
frail hawk
real thunder
#

so, I can't really afford Visual Studio to use performance wise
would Visual Studio Code or Vim with that server codecheck thingie work way better?

naive pawn
#

vsc code would definitely work

#

vim.. can't guarantee all the features, but you should probably be able to get c# set up?

polar acorn
#

God no, don't use Vim

real thunder
#

they say so but I am not sure it's feasible

polar acorn
#

why would you use Vim outside of a command line interface

real thunder
#

why should I not

naive pawn
#

vim is, afaik, just as much of an ide as vsc is

#

it's a text editor that's extensible

real thunder
#

I am not surprised

#

it gives an impression of being more gimmicky than vsc tho

swift crag
#

I used to use Visual Studio Code until I switched to Rider

naive pawn
#

wdym gimmicky lol

swift crag
#

Vim is good if you're the kind of person that likes Vim 😄

naive pawn
#

vim is just, a more barebones text editor

#

i don't know a lot of coding people but i do know one who uses vim as his main ide

swift crag
#

one of my professors in college was all-in on emacs

#

I used it for a bit but didn't really like it

#

we have mouse pointers and nice displays now , haha

naive pawn
#

and that's not uncommon; vscode (i think maybe monaco itself?) has support for emulating vim

#

and yeah emacs is on the same level but that's about as far as i know

naive pawn
# swift crag we have mouse pointers and nice displays now , haha

sometimes it's more convenient to not have to move your hand to a separate device to get stuff done
the close arrow keys on some keyboard layouts helps a lot with doing home/end/pgup/pgdown maneuvers
even on a laptop i use my thumb for the trackpad sometimes so i don't have to move my hand lol

real thunder
#

I ve basically watch a funny yt dude who said that using Vim's customizable hotkeys and cursor movement saves alot of time so

polar acorn
#

Visual Studio also has hotkeys

naive pawn
#

pretty much every viable ide has hotkeys

#

that's like, one of the things making them viable

real thunder
#

yeah he said most IDEs can emulate that
(I mean vim-motions)

swift crag
#

imagine not programming in VR with dance moves

#

🙄

naive pawn
long jacinth
frail hawk
#

what IDE is that

long jacinth
frail hawk
#

did you read what the bot recommends.

#

with that you can get intellisense working

hexed terrace
long jacinth
#

and the one that the bot reccomends

hexed terrace
#

yes, that's why I said what I did..

#

the bot doesn't recommend anything

long jacinth
naive pawn
#

try restarting the language server

#

ctrl+shift+p, search for .net, choose the restart language server option

swift crag
long jacinth
#

ok

frail hawk
#

keep in mind Visual Studio Code and Visual Studio are 2 different things.

swift crag
#

Ensure that you are not attempting to follow instructions for Visual Studio.

#

you are using Visual Studio Code.

#

(i know, the names are great)

frail hawk
#

agreed 😉

hexed terrace
#

!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

signal cosmos
#

!code

eternal falconBOT
long jacinth
#

is this 'proccessing workspace information in the background...' something i should worry about

swift crag
swift crag
#

Okay, so the Unity extension is installed properly

long jacinth
#

Package Manager

swift crag
#

That all looks good

#

Kill VSCode, then go to Preferences -> External Tools and regenerate the project files

#

then reopen VSCode by double clicking a script asset

swift crag
#

just quit VSCode

#

alt-f4 is actually the same as clicking the X button in the corner

#

so that does work 😛

long jacinth
swift crag
#

No, you can leave it as-is

long jacinth
snow warren
#

hi

#

i am having serious trouble

#
    {
        for(int i = 0; i < RigBase.transform.childCount; i++)
        {
            Transform child = RigBase.transform.GetChild(i);
            Debug.Log(child.gameObject.name);


            if(child.gameObject.name == name)
            {
                Debug.Log(child.gameObject.name);
                return child;
            }
        }
        Debug.Log("ReturnedNull");
        return null;
    }```
#

whenever i run a loop for children inside a gameobject

#

it returns me the child

#

but it displays the same name

#

anyone can explain why?

#

or is it an engine error?

#

ok i understand my problem

wintry quarry
snow warren
#

only the children that were actually inside it

#

not the the childrens that were inside the other childrens

#

so i took a shortcut

#
        return obj.transform;```
wintry quarry
snow warren
#

it can cause errors

wintry quarry
#

you would need to either use recursion or a stack

snow warren
#

ok

wintry quarry
# snow warren ok
    private Transform FindBoneWithName(Transform root, string name)
    {
        for(int i = 0; i < root.childCount; i++)
        {
            Transform child = root.GetChild(i);
            Debug.Log(child.name);

            if(child.name == name)
            {
                Debug.Log(child.name);
                return child;
            }

            Transform recursiveResult = FindBoneWithName(child, name);
            if (recursiveResult != null) return recursiveResult;
        }
        Debug.Log("ReturnedNull");
        return null;
    }``` A simple recursive approach
snow warren
#

ok

#

let me try

wintry quarry
#

you will need to initially call this with FindBoneWithName(RigBase.transform, "whatevername");

snow warren
#

thanks
let me try this one out

languid spire
#

should be

Transform recursiveResult = FindBoneWithName(child, name);
wintry quarry
#

@snow warren fixed the code as per Steve's suggestion

snow warren
#

isnt it the same thing?

wintry quarry
#

no

#

very important difference

#

this will work, the other way would not work (it would result in a stack overflow error)

snow warren
#

yea it resulted

wintry quarry
#

I changed FindBoneWithName(root, name); to FindBoneWithName(child, name);

snow warren
#

ahhhhh

#

now i get it

hybrid finch
#

hii guys im trying to make it so that damage gets taken away from the players health every 5 seconds , but after the first time the damage gets taken away without the 5 second wait, can anyone tell me what im doing wrong?

slender nymph
#

you start the coroutine every frame that the condition is true. starting a new instance of the coroutine does not wait for the previous instances to finish, so you end up starting hundreds of completely separate instances of that coroutine

nimble mortar
#

Is this message correct Physics2D.BoxCastNonAlloc is deprecated. Use Physics2D.BoxCast instead. since BoxCastNonAlloc allows you to get multiple hits and BoxCast only gives one, I am confused?

slender nymph
#

did you look at the documentation for Physics2D.BoxCast?

nimble mortar
slender nymph
#

i understand that is where the error message is coming from. i'm asking if you've even bothered looking at the documentation for BoxCast considering you've stated that it only gives one. but you can check the documentation to see that isn't the only case

nimble mortar
#

i did but obviouslyt missed something

#

nvm

#

I did miss it

slender nymph
#

yes, that was the point i was making

hybrid finch
slender nymph
#

well for starters, you don't even need a coroutine. simply incrementing a timer in the existing if statement in Update and only removing the health at set intervals would be sufficient. otherwise you need to track when the coroutine has started and ended

hybrid finch
#

ty ill use a timer

hybrid finch
slender nymph
#

google "unity timer"

hybrid finch
#

like this?

bright sequoia
#

How would you guys recommend best for learning Unity and C# programming for someone who just started?
I've done Microsoft's C# learning paths, but a lot of whats needed in Unity isn't taught in those beginner paths.

So should I just keep following tutorials for my first couple games until I get a hang of it? Should I mainly try and learn from just Unity documentation/other online forums and manuals?

slender nymph
#

there are beginner c# courses pinned in this channel. after completing them the pathways on the unity !learn site will help you learn how to use unity

eternal falconBOT
#

:teacher: Unity Learn ↗

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

bright sequoia
#

thank you 📦 friend salute

hybrid finch
#

@slender nymph wat am i doing wrong lol

north kiln
#

Time is underlined for a reason

hybrid finch
polar acorn
hybrid finch
polar acorn
#

the thing you type code in

bright sequoia
hybrid finch
polar acorn
#

You never use the variable, so it might as well not exist

#

so either actually use the value for something, or remove it

hybrid finch
polar acorn
hybrid finch
#

@polar acorn

polar acorn
#

Where does it matter what value that variable has

bright sequoia
hybrid finch
polar acorn
bright sequoia
#

no point in defining time if youre gonna set it to Time.deltatime

Thats like saying i=3 and then saying i=24 in the next line. Setting it to 3 is redundant

#

(i think)

polar acorn
#

There's no point in having a variable at all if you never use it for anything

#

At no point does this code do anything differently no matter what timee is

bright sequoia
#

ahhh just using deltatime in the first place then? JermaNote

polar acorn
#

It could be 3, it could be 24, it could be -525,600 and it doesn't matter

#

Nothing uses it

#

The code would be literally identical if the variable were just deleted entirely

bright sequoia
#

(srry ik this isnt my code im just siphoning ur knowledge)

AH, so bc his code either isnt finished yet or just doesnt use time in it at all ,thats why it isnt working YEA

polar acorn
#

Which is what I'm trying to ask. What the variable is for

#

what it's supposed to do

hybrid finch
polar acorn
#

What do you want to do with it

swift crag
#
float renderCoolGraphics = 3;

no amount of wishful thinking will cause this to do anything on its own

swift crag
mental palm
#

Hey guys weird questions

Im making a CookieClicker knock off (lol) and i need to check if the cookieAmount ist bigger than a certain variable (milestone)
that works perfetcly until you reach 1000 cookies... I tried

Debug.Log(CookieCount > 1000) ```

wich prints: 1,045 and false wich is ridiculous 
my CookieCount is stored as a double and in the inspector it shows 1045 and in other scripts it behaves like its 1045 but i feel like this if statement in particular is reading the 1045 as 1,045(decimal)

Does anyone know anything about that?
swift crag
#

notably -- make sure that "Collapse" is disabled in the console

#

that could cause very misleading results

#

it combines duplicate messages together

mental palm
#

its in update function so it prints false once per frame XD

swift crag
#

If CookieCount contains a value of 1045, then there is absolutely no way for CookieCount > 1000 to return false

teal viper
#

Share the actual code

#

The whole method

swift crag
#

yes, please

mental palm
#

ok wait a seconf

warm shore
#

can someone explain how i get my e click to stop playing sound ive been trying all day

mental palm
#

the script is a little spgatetti code ish so dont judge lol

swift crag
#

Can you send that using a paste site? !code

eternal falconBOT
teal viper
polar acorn
# warm shore

Why are you checking the name of this object? Don't you already know what object it's on by virtue of putting the script on that object?

mental palm
swift crag
#

yep

mental palm
#

nice

swift crag
#

I do not see any lines that match the code you posted. Are you talking about lines 92-94?

mental palm
#

yes

warm shore
#

i set to false that didnt worrrk

mental palm
#

92-94

swift crag
teal viper
warm shore
#

in the same script whenever i press left on the box it plays music

#

so i know part of it work

swift crag
#

How do you know that this code is running?

mental palm
warm shore
mental palm
#

the weird thing about it is that everything works consistent up until 1000

swift crag
#

You can find out if it is by adding some debug statements, yes

#

Put some log statements inside of both if statements

#

as well as before that entire block of code

#

find out what, exactly, is happening

warm shore
#

ok

swift crag
#

the second one could saying "True" while the third one is saying "False"

mental palm
#

they both say false

swift crag
#

Show a screenshot of your console

mental palm
#

aight

swift crag
#

(the entire console window)

mental palm
#

ah wait

swift crag
#

are you French, by any chance

mental palm
#

german

swift crag
#

hm, maybe..

#

because that would cause a number between 2 and 3 to render as 2,5

#

Oh yeah

mental palm
#

??? wut

swift crag
#

The German decimal separator is a comma

mental palm
#

cause im German XD

#

yeah it is

#

we type 4,5

swift crag
#

Your number is actually very small

mental palm
#

yeah so it does read the 2000 as 2.0 right?

#

but i dont understand why cause in the inspector of my Game mananger script (holding the cookie Count variable) it says 2000

swift crag
#

to sanity check, actually type in 2000 into the inspector

#

This will have no effect on how comparison works

#

It'd strictly be how the number gets turned into a string

#

If you typed in 2,000 into the inspector, it's possible that you'll get a value of 2

#

I'm not sure how that works out

teal viper
#

Could cast it to an int before printing

mental palm
#

Debug.Log(2000) ?

swift crag
#

Set the number of cookies to 2000.

#

Type it into the inspector.

mental palm
#

ah ok

swift crag
#

don't type 2,000 or 2.000 or anything else

mental palm
#

gimme one sec

#

so it says 2000 in the inspector but 2 in the console

#

wtf

#

as soon as i tap a little it goes to 2, something

swift crag
#

Your inspector is in debug mode. You should put back into the normal mode

#

click the little three-dots button in the very top right

mental palm
swift crag
#

ah

mental palm
#

yeah yeah ik

swift crag
#

what is "unformatted cookie count"?

#

It sounds like you're doing something very weird here...

mental palm
#

im not a complete beginner i have like 2 years of unity but im a little stupid sometimes

swift crag
#

share the entire script for the cookie manager

#

ah, yes

#

this is your problem

#

you are dividing the cookie count by 1000 here, then calling CheckSlider

#

2000 has become 2

#

You were seeing 2,123 or whatever because that's your decimal separator

mental palm
#

so as you see in update cookie text the 1000 is formatted into 1a so i thought that might affect the cookieCount so i initialized a variable called unformated cookies 💀 for debug but its not used i think

swift crag
#

if you used an American culture to turn that double into a string, you'd see 2.123

mental palm
#

so thats what i thought the formating of the numbers affects the value, but why does it still show 2000 in the inspector

swift crag
#

Because the original number isn't getting changed

mental palm
#

OH BECAUSE THE DOUBLE cant show decimals

mental palm
swift crag
# swift crag

cookieCount is an argument to the method I screenshotted here

#

It's getting divided by 1000

#

The original number (which lives over in the "cookie manager" class) is not being changed

mental palm
#

ahhh but i pas the argument instead of refering back to the original value

#

yeah well thats wuite stupid

swift crag
#

comma decimal separator jumpscare

mental palm
swift crag
#

If you got up to a cookie count of 1234567, you'd see 1,234567

mental palm
#

wait what ?

#

o true

swift crag
#

your code would divide by 1000 twice

mental palm
#

yeah just realized

#

@swift crag IT WORKS

#

thanks for helping me

#

also wtf you are smart fucking detective moment when you asked if i was french lol

swift crag
#

I've seen this kind of thing once or twice haha

mental palm
#

i see

swift crag
#

(although, mostly with problems parsing data)

#

this was the opposite

#

definitely a funny connection to make, haha

mental palm
#

If just recently seen a video telling me to pay close attention to the difference between copies and refernces but because it said cookieCount ( and i wasnt in this project for a longer time) i thought that was the original value i didnt even question it

fading mountain
#

I'm getting a null reference exception when I start the game on line 40 of CircularSpawner.cs https://hatebin.com/ecvydozvpw. This could be because of currentSheep being null instead of the newly instantiated sheep, or it could be an issue with setting the currentSheep spawner to this instance. The public method being called is in line 179 SheepMovement.cs https://hatebin.com/yfosmotlzd. Please let me know if you need more info.

slender nymph
#

if the NRE occurs on line 40 and not within the method called on line 40, then currentSheep is null which means the instantiated object does not have a SheepMovement component on it

#

but also, if you use the actual component you care about as the type for your prefab variable (in this case objectToSpawn) then Instantiate will return the correct component so you won't need the GetComponent call. it will also prevent you from adding the wrong kind of object in the inspector

fading mountain
slender nymph
#

not according to the error

fading mountain
#

like grass

slender nymph
#

then why does the spawn method depend on a specific kind of component? obviously that will throw an exception when used with literally any other object

fading mountain
#

ahh

#

thats the problem

#

thank you boxfriend 👍

slender nymph
#

i'd recommend instead defining an interface that has this SetSpawner method then using TryGetComponent to get that interface on the instantiated objects so you can then pass this to it. Then just have SheepMovement implement the interface. you can also completely remove the if statement inside of the loop, the overload that accepts a parent just calls the one that doesn't if the parent parameter is null

#

so then the contents of the loop just ends up becoming:

var instance = Instantiate(objectToSpawn,
  (Random.insideUnitCircle * spawnRadius) + origin,
  Quaternion.identity, 
  objectContainer);
if(instance.TryGetComponent(out ISetSpawnerInterface setSpawner))
{
  setSpawner.SetSpawner(this);
}
fading mountain
#

👍 I'll give it a try. thank you

slender nymph
#

also make sure to choose a better name for the interface, that was just an example since i don't know what the actual purpose of calling that method is (other than what is hinted at by the name)

fading mountain
#

I named it ISpawnable

sharp pawn
#

If I have the line the line of code
If (Input.GetMouseButtonDown(0))
Is there something that lets me activate code when the player clicks and then a separate set of code that activates when the player releases the mouse button if they are holding it down?

slender nymph
#

GetMouseButtonUp will be the one you want to check for releasing the button

sharp pawn
#

For context I am making a weapon that fires a laser the laser is just a cylinder that I want to become active when the player starts the click and becomes inactive when they release the mouse button

slender nymph
#

then why not just use GetButton instead of GetButtonDown? otherwise, i already told you what you can use to check when the button is released

sharp pawn
#

Not on the best wifi rn didn’t see it

#

But still thank you

#

Ok that works perfectly thank you

frosty field
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

warm flame
#

I keep getting object reference errors for the slider, what am I doing wrong here?

#

using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
using UnityEngine.UI;
using VRC.Utility;

public class Slider_Cube : MonoBehaviour
{

    private Slider slider;

    public Transform anchor_1;
    public Transform control_1;
    public Transform control_2;
    public Transform anchor_2;

    public GameObject cube;

    void Start()
        {
        slider = transform.GetComponent<Slider>();
        cube.transform.position = anchor_1.position;
        }

    void OnEnable()
    {
        slider = transform.GetComponent<Slider>();
    }

    // Update the cube's position
    public void SlideUpdate() {
        Debug.Log(slider.value);
        cube.transform.position = BezierPoint(slider.value);
    }

    // Calculate the vector at the point along the line
    private Vector3 BezierPoint(float t) { ... }

    // Draws white line showing the bezier's path
    void OnDrawGizmos(){ ... }
    
}

#

The error points to first line in SlideUpdate

timber tide
#

You've the idea with the logging. There's only a few other things that can be null so keep trying

#

Well, here's some more advice. Make sure you log the object before trying to dot access its values

warm flame
#

I'm confused on what the lifecycle is, when it comes to editor and runtime event invokations.
I thought Start(), Awake() or OnEnable() would allow setting some fields before any events began firing.

wintry quarry
warm flame
#

you mean just use public/serialized fields?

wintry quarry
#

Yes

warm flame
#

I suppose so; I was trying to keep things encapsulated. But it seems it's not possible, or not in a clean way

polar acorn
rocky wyvern
#

idk about onenable but awake isn't called on domain reload

#

oh u used start

#

yeah use awak

#

then readd the script

#

otherwise the reference won't be there except in runtime

burnt vapor
brave tapir
#

why is my 2d game looking all weird like this, is my text too small in text mesh pro?

warm flame
#

I'm getting a UnityEventFilter error, telling me events on Slider were removed because one of them targeted a prohibited type. What does this even mean?

verbal dome
#

So everything you see in the bottom of the console with that error selected

warm flame
# verbal dome Show the whole error, including the stack trace?
[UnityEventFilter] Events on 'Slider' were removed because one of them targeted a prohibited type 'SliderCube', method 'SlideUpdate' or object 'Slider'.
UnityEngine.Debug:LogWarning (object,UnityEngine.Object)
VRC.Core.Logger:LogWarning (string,int,UnityEngine.Object)
VRC.Core.UnityEventFilter:LogRemoval (string,UnityEngine.Object) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:442)
VRC.Core.UnityEventFilter:FilterUnityEvents (System.Collections.Generic.HashSet`1<object>,VRC.Core.UnityEventFilter/TypeInfo,object,UnityEngine.Component) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:360)
VRC.Core.UnityEventFilter:FilterUnityEvents (System.Collections.Generic.ICollection`1<UnityEngine.Component>) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:322)
VRC.Core.UnityEventFilter:FilterUnityEvents (System.Collections.Generic.List`1<UnityEngine.GameObject>) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:278)
VRC.Core.UnityEventFilter:FilterEvents (System.Collections.Generic.List`1<UnityEngine.GameObject>) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:254)
VRC.Core.UnityEventFilter:RunFilteringOnPlayModeEntry (UnityEditor.PlayModeStateChange) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:125)
UnityEditor.EditorApplication:Internal_PlayModeStateChanged (UnityEditor.PlayModeStateChange)
verbal dome
eternal falconBOT
torpid igloo
#

I'm trying to add force only to the x axis but it doesnt work. when i check in the RigidBody2D component of the object im trying to move it shows the attached video when i click the mouse button. this is my script, please help.

private void FixedUpdate()
{
    _mode = _wheelScript.CurrentMode;
    WaterControl(_mode);
    WindControl(_mode);
}

private void WindControl(Mode curMode)
{
    if (curMode != Mode.Wind) return;
    if (Input.GetMouseButton(0))
    {
        Debug.Log("Click");
        _rb2dBoat.AddForceX(windSpeed);
    }
    else if (Input.GetMouseButton(1))
    {
        Debug.Log("Click");
        _rb2dBoat.AddForceX(-windSpeed);
    }
}
#

It prints out the "Click" message so it isnt something with the inputs

languid spire
#

Do not read Input in FixedUpdate

torpid igloo
#

istg it was in update and didnt work, so i changed it to FixedUpdate and it still didnt work, and now it works

#

when i set the windSpeed variable to something smaller than 8, it stops moving the object

hexed terrace
#

because it's not enough force

teal viper
#

Probably a combo of missed input(due to fixed update) and friction.

torpid igloo
teal viper
#

Also, add force should be in fixed update.

torpid igloo
#

but @languid spire told me to not read input in FixedUpdate

#

you can read it a bit up the thread

languid spire
#

You read Input in Update you consume it in FixedUpdate in your case

torpid igloo
#

and how do i do that? this feels like a dumb question but i actually dont know how

teal viper
languid spire
#

something like

bool pressed = false;
void Update() {
   if (Input.GetKeyDown(KeyCode.space)) pressed = true;
}
void FixedUpdate() {
   if (pressed) {
     pressed = false;
     //DO STUFF
   }
}
torpid igloo
#

so this?

bool pressedLeft = false;
bool pressedRight = false;

private void Update()
{
    _mode = _wheelScript.CurrentMode;
    
    if (Input.GetMouseButton(0)) pressedLeft = true;
    if (Input.GetMouseButton(1)) pressedRight = true;
}

void FixedUpdate()
{
    WaterControl(_mode);
    WindControl(_mode);
}

private void WindControl(Mode curMode)
{
    if (curMode != Mode.Wind) return;
    if (pressedLeft)
    {
        Debug.Log("Click");
        _rb2dBoat.AddForceX(windSpeed);
        pressedLeft = false;
    }
    else if (pressedRight)
    {
        Debug.Log("Click");
        _rb2dBoat.AddForceX(-windSpeed);
        pressedRight = false;
    }
}
#

it doesnt move at all now

#

even if the windSpeed is 8(what worked before)

verbal dome
#

GetMouseButton is perfectly fine in FixedUpdate. GetMouseButtonDown is not

burnt vapor
#

I guess the issue is that it is possible your input is not registered if you somehow press your mouse between the frames where FixedUpdate is not invoked

#

It is technically fine, but it can not register input if you are the Flash

torpid igloo
# verbal dome GetMouseButton is perfectly fine in FixedUpdate. GetMouseButtonDown is not

i changed the code like you recommended:

private void FixedUpdate()
{
    _mode = _wheelScript.CurrentMode;
    WaterControl(_mode);
    WindControl(_mode);
}

private void WindControl(Mode curMode)
{
    if (curMode != Mode.Wind) return;
    if (Input.GetMouseButton(0))
    {
        Debug.Log("Click");
        _rb2dBoat.AddForceX(windSpeed);
    }
    else if (Input.GetMouseButton(1))
    {
        Debug.Log("Click");
        _rb2dBoat.AddForceX(-windSpeed);
    }
}

and it still doesnt work

languid spire
#

why not log _mode

torpid igloo
#

it still prints out "Click" so it runs

burnt vapor
#

What is windSpeed here?

#

Log that

#

Especially since none of your code has any context around this variable, it is entirely possible you changed this by accident

torpid igloo
#

it doesnt change. i only set the value of it in the editor

verbal dome
burnt vapor
#

Very, very unlikely

verbal dome
#

In that scenario, caching the mouse press state in updates o and m would still result in the mouse press being false in the second x

#

I don't think there's a difference between caching the value in Update or just using GetMouseButton in FixedUpdate

#

Since fixedupdate always has the most recent frame's input

torpid igloo
#

@burnt vapor if it helps, i found that the linear velocity values change on the rigidbody of the object but the X position doesnt change.

hexed terrace
#

not got constraints enabled have you ?

torpid igloo
#

no

#

because i need the y position to not be frozen(for another thing in the game)

verbal dome
#

If my testing methology is correct, you might event get one frame old inputs if you cache them in Update and use in FixedUpdate```cs
int frame => Time.frameCount;

bool pressedUpdate = false;
bool pressedFixed = false;

void Update()
{
var p = Input.GetMouseButton(0);
if (p && !pressedUpdate)
Debug.Log($"Mouse press detected Update {frame}");
pressedUpdate = p;
}
void FixedUpdate()
{
var p = Input.GetMouseButton(0);
if (p && !pressedFixed)
Debug.Log($"Mouse press detected FixedUpdate {frame}");

pressedFixed = p;

if (pressedFixed != pressedUpdate)
    Debug.LogError($"Most recent mouse state from Update was incorrect {frame}");

}```

#

Because in some fixedupdates the cached update value is not up to date

#

(This is specifically for the scenario where you only use the inputs in FixedUpdate)

languid spire
verbal dome
#

It would be false, no? So you miss it anyway?

#

If the bool is used like a trigger, then it would make sense
Like keep it true until used

languid spire
#

no, you cache only when pressed.
Read in Input. Consume in FixedUpdate

verbal dome
#

So you don't set it to false when you release the mouse in Update?

#

Note that I'm talking about GetMouseButton, not GetMouseButtonDown

languid spire
#

no, only when you have used it in Fixed

verbal dome
#

Talking continuous input here

verbal dome
languid spire
#

for continuous input in theory you are correct but, because of potential hardware buffering on the device, it is much better to clear the input buffer on a frame by frame basis

rocky wyvern
#

it would be set to false in the next update

verbal dome
#

So pressing and also releasing the mouse between fixed updates

#

Which is a valid concern yeah. Easily reproducible if you set fixed time step to 0.1+ seconds

#

I think the most robust way would be to use a combination of fixedupdate and update input

#

To solve both the "press and release between fixedupdates" issue and the potential one frame delay

rocky wyvern
#

well reading back

#

why did people say to not use getmousebutton lol

verbal dome
#

Well there's the edge case issue that we were discussing 🤷‍♂️

rocky wyvern
#

I mean its so minor

#

if u click in >20ms

#

hats off tbh

verbal dome
#

Yeah. More of an issue if your fixed timestep is higher

torpid igloo
#

@languid spire maybe the problem is in my rigidbody settings?