#💻┃code-beginner

1 messages · Page 824 of 1

naive pawn
#

line 12, column 45

solar hill
#

It should still underline the error then, and tell you you have one

static socket
#

How to i select the collum

naive pawn
#

(you may also see something like Flow.cs:12 in other contexts, only showing the line number)

naive pawn
solar hill
#

Just go to line 12

static socket
#

private struct RecursionNode : IEquatable RecursionNode

naive pawn
#

it's only necessary if you have 400 long lines

static socket
#

line 12

naive pawn
static socket
#

where is it missing?

naive pawn
#

did you perhaps accidentally modify this file?

solar hill
naive pawn
#

it seems like this is from an asset so it shouldn't have this issue on its own

static socket
#

Its from a decompile

naive pawn
#

ah.

solar hill
#

Uh oh

#

No no no

naive pawn
#

of course

polar acorn
solar hill
naive pawn
solar hill
#

Not here

polar acorn
naive pawn
#

(btw, the error says the opposite of this.)

polar acorn
solar hill
#

It has an extra symbol somewhere

polar acorn
#

No, it's missing a symbol

solar hill
#

But its also a decompile so lord knows what could be fucked up

#

Did i not say that then initially

#

What

#

Ah fuck

#

I said the same thing twice

polar acorn
#

Because that line isn't the syntax for implementing multiple interfaces

solar hill
#

I am very... tired atwhatcost

earnest wind
#

what is my mistake im just so tired..

naive pawn
#

what's the issue

polar acorn
earnest wind
#

give me on second

#

im collecting some photos for that rn

earnest wind
# naive pawn what's the issue

altough camera is close to some other objects that have the lod script, only 3 that are the closest to origin are chosen to be on?? here is my set up for manager and for individual poles

#

all i want is to just turn lights on when you are 15 units away, it just does it for these 3 that are closest to origin?

#

even if I manually put a camera as variable instead of getting the Camera.main i get the same result, so its not that kind of problem

timber tide
#

doesn't unity's LODs do this for you already

earnest wind
timber tide
#

it'll swap meshes with enable behaviours if attached

ivory bobcat
#

So you're saying that the problem is: only three lights near the origin of the world are turned on when approaching the lights?

earnest wind
#

i recorded a video with debug logs, ill show right now

#

wait i compressed it

#

also it says 2 because i added a second distance to test

#

but yes, same result

#

also yes, it is from origin, for some reason

ivory bobcat
#

I've got to run but show your lod component array, log the positions etc so that others can help you better (they may not be where you think they are)

earnest wind
#

here is the radius and position from OnDrawGizmosSelected

just changed the last line to Gizmos.DrawWireSphere(pos, manager.Distances[i]);

earnest wind
#

NOOO

#

No way...

#

i forgot to write this line of code

opal zodiac
#

Anyone here experienced with inventory systems? i got a primitive one setup that can hold quantities, icons, descriptions and image displays but idk how the hell to drag and drop items

teal viper
opal zodiac
teal viper
#

Yeah. You wouldn't find a tutorial for every specific case.
For drag and dropping specifically, you should learn how drag and dropping ui elements work. Nothing to do with inventories on its own.

timber tide
#

I wouldn't sweat too hard on making one. Make it as primitive as possible and forgo any loose coupling

opal zodiac
timber tide
#

Unity complicates stuff as you can store backend code on those UI components

teal viper
opal zodiac
timber tide
#

https://www.youtube.com/watch?v=bTPEMt1RG3s
Go with this series if you want to follow something. Gives you a rundown of all of unity's features you'll probably be using and you may learn a few things.

Tutorial series on how to make an inventory system in Unity, using C# and the Unity UI. In part 1 we build the base UI, implement Items using ScriptableObject and make the Inventory class. We'll also use the Character Stats asset (developed in another tutorial series).

► Next Video (Part 2): https://youtu.be/4JewzU_phTM
► Items & Inventory ...

▶ Play video
final rune
#

can we discuss this in dm. Thanks

grave osprey
#

Hey all! I'm trying to implement a simple exploration system in my game. The entire map should be hidden at the start besides where the player is, and anywhere where the player goes gets revealed permanently.

How would I go about doing this? I've currently got a large, flat cylinder attached to the player that represents their vision. How do I go about storing where they've explored, and only revealing areas after the fact?

grave osprey
prisma shard
#

I should have asked this yesterday but can someone tell me how to find unity assets or frankly prebuilt things in general that would properly fit the architecture of a planned game? i do not want to reinvent the wheel so it'd be awesome i know where and what to get the things i need.
i mean like pathfinding, grid systems, maybe some kind of ease of action queing system etc. And the 2nd part of the question is still on finding out what i need since im a beginner

timber tide
prisma shard
timber tide
#

Eh, I ideally you just learn from it. You can probably grab scripts and paste them over into a new project, but usually there's a bunch of dependencies that it makes it pretty hard.

prisma shard
#

I thought programmers are suppose to be decoupling code blocks. Damnit. So im back to square one of need individual unity asset systems so i dont reinvent the wheel

timber tide
#

There's usually multiple ways to go about something. Like a tower defense game you can just build a 2D grid and do it by index placement, or have a freeform environment to build upon and use colliders for placement.

sour fulcrum
#

there's no magic solution where you get to completely avoid programming here

#

even putting two completely separate solutions together is gonna be work

prisma shard
#

i understand but skipping parts that could take ages to do, seems... important

sour fulcrum
#

potentially yeah

prisma shard
#

Anyone know how much it would cost to hire a programmer babysitter? I always hear compsci people complain about being terminally unemployed but if that were true they would be pretty cheap would they not?

sour fulcrum
#

we dont really do that here

prisma shard
#

I am not looking to hire someone here im asking how they would cost

sour fulcrum
#

and most places adjecent to here would not be recomending you pay people below minimum standard rates in their country so it depends

#

depends on where they live

prisma shard
#

Tbh even so that compsci whining about being unemployed sounds fake. There is rarely times i have hired people outside of house improvement. That i would want to hire a specialiy job like that even though im not a company should mean they are in high demand

sour fulcrum
#

Stupid ass statement

timber tide
#

usually around 40 I'd say is the average rate, but always people offering for less if you look around

prisma shard
#

interesting thanks, id hope they be cheaper because im not expecting them to code just to babysit. but ill see about it

vast matrix
#

Hello, I am trying to create a system where once the player enters within a certain distance of an enemy the enemy attacks the player with lightning (Marked by a red circle on the ground). Everything is working fine except I can't seem to figure out how to apply damage to the player if they are in the circle at a certain time. Could someone explain to me how I would do that?

timber tide
prisma shard
#

lol probably but ur not just developing the game but also learning so ur getting a teacher as well

vast matrix
sour fulcrum
prisma shard
sour fulcrum
#

Ah misunderstood what you said, apologies

hushed flame
#

Hi, I'm here because of the graffiti video. I'd like some help figuring out how to do it. Look, I already have a yellow line, which is the raycast. But what do I do to paint the wall? I already have that yellow line coming from the player. But I still need to paint the wall.

timber tide
vast matrix
timber tide
#

delta time

vast matrix
#

Oh thank you

#

Yeah that makes sense Ill try that

prisma shard
#

how does delta time work again? i think i remember it having a problem with a late 0.3 tick system

#

or perhaps i needed to just use frame interpolation smoothing for sprites or something

timber tide
#

can also just compare Time too since this isn't something that requires that much precision anyway

hushed flame
#

Hi, I'm here because of the graffiti video. I'd like some help figuring out how to do it. Look, I already have a yellow line, which is the raycast. But what do I do to paint the wall? I already have that yellow line coming from the player. But I still need to paint the wall.
Help.

slender nymph
#

surely whatever resource you used to learn about the topic covered that?

timber tide
prisma shard
#

by frame u mean the registry of the whole system right? like ingame data updating

timber tide
#

From Software loves to always have some mechanic each game where they do just that such as weapon durability becoming a larger problem if your monitor refresh rate was higher than average.

prisma shard
#

i feel like i am going to start crying when i get later into development, that sounds absurdly annoying

#

just ridiculously stupid bugs like that of data tied to monitor hz

timber tide
#

Elden Ring had some hitbox issues earlier on where character invulnerability was tied to that too so you would instant die to some enemies if your refresh was higher.

prisma shard
#

oh if its even in AAA games that makes me feel slightly better. What a weird bug

timber tide
#

It's mostly because these games are usually locked at a frame rate, but PC releases they allow for higher rates. Elden Ring though is actually locked at 60 unless you do modify the game.

prisma shard
#

well clearly they cant just fix the framerate issue without breaking the code in a major way. the spaghetti code problem seems to be quite depressing for many people. ive heard of compsci students even dropping out of it as a major just for that reason

sour fulcrum
#

no they can

#

they just aren't interested in doing so

prisma shard
#

like it would be too much work? sounds simple to me (tho i barely know shit)

sour fulcrum
#

i guess

#

anything can be too much work depending on what you consider too much

north verge
#

Can anyone help with me with my code, im trying to have Slope rotation what is smooth with my player. And i have it in but its pretty bad, And its just stubby.

inland pecan
#

Whats the difference between doing

private int Num;

and doing

int Num;
wintry quarry
#

private is the default access modifier for fields

#

If you're trying to declare a local variable, then the private one would be a compile error.

real gorge
inland pecan
#

Alright thanks to both of you

verbal dome
final rune
queen vale
final rune
verbal dome
final rune
silent sorrel
#

so im trying to transfer those int into my second script and i want to be able to modify is from both is side

#

i just cant seem to figure it out ive been trying for 2-3 days

undone rampart
#

make it public

silent sorrel
#

but it is

#

not the addingx

#

all the rest

undone rampart
#

ah

silent sorrel
#

lol sorry realise i was highlighting it

undone rampart
#

is the class also public?

silent sorrel
#

YES

undone rampart
#

do you have a reference of this script to the other script?

silent sorrel
#

no

#

and every tutorial ive seen are different

undone rampart
#

if you want to access any members of a script in another script you need a reference to it

silent sorrel
#

how do i do that

undone rampart
#

so in the other script you create a new variable of that class, assign it, then you can call that variable and access all its public members

silent sorrel
#

OO

naive pawn
silent sorrel
#

thank u

naive pawn
#

you'll probably want serialized references

silent sorrel
#

will read all that

upper yoke
#

Hey, I'm making a simple level where you throw a disk around, parts of the maps are overlapping and even if colliders are at the same height the disk keep bumping on the jointure, what would be the best way to fix that?

undone rampart
upper yoke
cold slate
#

is there a way to fix this. the script i wrote is grayed out. the variable is missing

wintry quarry
#
  1. Check your console window for compile errors
  2. Make sure the variable is public or has [SerializeField] and is a type that can be serialized
cold slate
#

in player movement(script)

#

it should show Move

wintry quarry
wintry quarry
inland crystal
#

The script itself isn't greyed out. It's only the Script name that is in grey - because you can't change that in the inspector.

wintry quarry
#

Again. make sure:

  • your code is saved
  • it has no compile errors (check the Unity console window)
  • It has refreshed (ctrl+R iin Unity if you have auto refresh disabled)
cold slate
#

yeah i saved it

#

i assumed id be able to change numbers in it

wintry quarry
#

have you checked the console window for errors?

cold slate
#

maybe ill need to recheck the code

inland crystal
#

you can only get properties in the inspector if the field is public or serialized

wintry quarry
#

Show us your console window and show us your code

cold slate
#

theres no issues from visual studio

wintry quarry
#

I'm asking about Unity's console window

polar acorn
cold slate
polar acorn
#

Hey there you go

cold slate
polar acorn
#

Errors

#

You need to fix those

wintry quarry
#

also if your VS was saying there is no issue, you need to configure Visual Studio

cold slate
#

seems that way

wintry quarry
#

!ide

radiant voidBOT
cold slate
#

alright ill try see if i can fix it from there. thanks yall

#

yall were right about it being the errors. its odd it didnt show in visual studio but its fixed now. thanks again

wintry quarry
cold slate
#

alright will check that

north verge
mint flicker
#

Hi i dont know where the help chanle is

#

i dont know if i missed soemthing but in unity 3d the 2d png objects arent reacting with lights dont know why

solar hill
#

what exactly?

#

spriterenderers?

mint flicker
#

i will show

mint flicker
#

the object in the back is a 3d plane that reacts to light but not the png

#

heres the settings i think might helps

timber tide
#

sprite render isn't affected by 3d lights

mint flicker
#

how do i fixs it then

timber tide
#

custom sprite shader

mint flicker
#

is it easy

timber tide
#

HLSL? no. But possibly can plug it into lit inside of shader graph?>

mint flicker
#

i will trys

timber tide
#

hmm I think sprite lit just means 2D lights

#

I just remember it being a pain with shader graph but it's been a while. May be able to do it with just a lit graph nowadays

stone oar
#

hello, i have a question. i have a script that turns a specific object to face another object that I use for head rotation on animated rigs (very simple script, it's just Quaternion.Slerp in LateUpdate). the problem is - when i disable the animator component and enable it back - suddenly the head turn stops working and it locks the head in the last rotation it had. it slightly jitters (my guess) attempting to rotate towards the target, but it can't. constantly disabling and enabling the animator component causes the head to rotate and then stop, so my guess is that animator sort-of locks the bone. also happens on disabling and re-enabling the object. i applied the mask to the animator base layer, so im out of ideas for why it can be the cause. what might be the cause of this issue?

rich adder
#

Animator normally overrides transforms, iirc there is an option to disable that

stone oar
#

masking out the bones in the import settings does help, but sometimes the animation should still play, and applying mask to the animator layers seemingly does not work.

stone oar
frail hawk
#

may i ask why you are enabling and disabling the animator at all?

rich adder
stone oar
#

it doesn't happen only on animator disable

frail hawk
#

same question applies to the go

stone oar
waxen herald
#

guys can i delete the cooldown after jumps? cuz after landing on the ground there is a little time around 2-3s when i cannot jump

stone oar
waxen herald
#

okay, it is fine if i paste here?

frail hawk
#

yes, use code block or a paste bin

#

!code

radiant voidBOT
waxen herald
#

the // in hungarien if i forget

frail hawk
#

ok

#

if you want a slightly earlier isgrounded detection you would use a raycast

#

before you land the rc would detect the ground a few ms earlier, this will allow you to jump with nearly no delay when you land

wintry quarry
#

Another option would be to store the user's jump intention for a few milliseconds after they press it and immedaitely jump if you become grounded during that time.

frail hawk
#

also a decent idea

waxen herald
#

thank u guys

mint flicker
timber tide
#

assuming your method doesn't already implement it. I forget which has priority

vast matrix
#

How do I get BuildNavMesh to only apply to certain objects. Currently it's trying apply onto every object which causes errors.

soft lotus
#

How do i achieve better blending between 2 rule tile sets

rich adder
vast matrix
#

Thank you

rich adder
soft lotus
frail hawk
#

couldnt find a newer doc, but it is pretty same concept

timber tide
#

Last time I dealt with unity's nav tools I remember having to disable gameobjects and bake it for stuff I didn't want to bake on lol

rich adder
vast matrix
#

It says that Navigation Static has been deprecated

rich adder
#

well yes cause as mentioned global bake isn't a thing anymore

#

Navmesh surface lets you chose which objects to bake, you have several options on how to approach that

#

one Mao mentioned could also be an option

#

navmesh surface has an option to only bake on "children" gameobjects you could also use that so like temporarily make the navmesh objects the child of navmesh surface gameobject, bake and unparent

vast matrix
#

Okay I got it to work

#

thank you

timber tide
#

would make more sense to have a tag system for it tbh

#

but knowing unity they would tie it to your physical layers

rich adder
#

layers or tags wouldnt make sense because it would brake other things..
these are the options

#

modifiers can do a lot of the heavy lifting but its quite annoying having so many components on random objects

#

but beats having to use that "Static navmesh" option per object, that was also annoying just less a component

frail hawk
#

time to make an asset then

rich adder
#

the A* project iirc had a solid navmesh before unity changed it, I wonder how they did it. I only had the free version for 2D but heard the 3D had good things

solar hill
#

Unity sort of caught up with them

timber tide
#

it's just better

solar hill
#

the free version is kinda unnecessary now

#

while the paid one is still strictly better

rich adder
#

I think the runtime bake was only specific to that asset

timber tide
#

does unity even have 2D navmesh yet

rich adder
#

sadly no

solar hill
#

oh wait

timber tide
#

lel

solar hill
#

is this for 2d?

rich adder
#

A* path project did 2D but as actual grid not navmesh only the 3d one
the 2D one from h8man on github uses the Unity navmesh iirc but for 2D not sure why unity couldn't just do the same

timber tide
#

Unity's navmesh is actually fine for 3D. But their agents and avoidance is primitive

#

So if you are making an RTS game, Unity's agents fall flat instantly

rich adder
#

it takes a lot of fiddling to get some real solid results and even then requires you to manually mess around with the pathways

#

like getting only the path then process it yourself to add some curve to it or making it slightly longer / not so robotic.
by moving the agent using those point but agent.Move insteadof the SetDestination

#

downides of only using "shortest path"

#

check out people like LlamaAcademy they go indepth with this stuff

timber tide
#

The big problem is the API for the agents is limited. It's less like a motor and more like you see is what you get and don't think about modifying it further.

rich adder
#

to be fair for most basic usecases it just works

timber tide
#

Yeah true, it's more like a teaser until you want to actually put some money into it.

rich adder
#

like some of the problem like them being "singlefile" when putting 1 destination is easily solved by adding several points to try to "surround" player and so on

#

every horde zombie shooter in unity "SetDestination(player.position)"
done
🙄

timber tide
#

Good way to add some variance to updating the path, so they aren't always dead eye on you

#

let them overshoot the location sometimes so they can get around you

rich adder
#

yea exactly, you gotta play around with the chosen destination then switch up later when certain distance or something

#

main pet peeve for me , when multiple agents are in a narrow hallway and especially going in opposite direction and they get stuck 🤦‍♂️

timber tide
#

a* project is all about the avoidance and fixing these issues but otherwise Unity's fine for some smaller dumb AI games

rich adder
#

iirc unitys navmesh used older version of RVO but I think now its some other custom solution

timber tide
#

I just know that if you have 30+ agents together with Unity's agents and RVO enabled the game fps just tanks

stone oar
#

and other options are either free a*, paid a* or custom thing that will take months or years

#

tho there might be more pathfinding solutions if you're willing to pay

elder hearth
#

Hi-ya! I need to make my Start method in a script to wait 5 frames after it should be called to do the things inside. IS there a way to do this?

slender nymph
#

Start can be a coroutine, but that also sounds odd, why does Start specifically need to wait 5 frames?

elder hearth
slender nymph
#

why is the component "only made in Start"? why can it not be made in Awake?

elder hearth
slender nymph
#

sounds like the object that needs a reference to it should actually just be subscribing to an event that the spawned object invokes when it is spawned

slender nymph
#

create an event on the object being spawned, invoke that event at the correct timing you'd like. have the other object subscribe to the event before it is invoked

elder hearth
#

k thx

arctic island
#

I have been using unity assets for my game character. The only problem is I want more animations. Is there a good video tutorial on how to create animations for existing models?

rich adder
upper token
#

I found out :D

timber tide
#

3D sorting transparents

gaunt cipher
#

does anyone get this bug or know how to fix it where you go into a prefab, set a number, then exit the prefab and it isn't saved properly?

Like I go and try to make the width of something 150, even press ctrl+S to save, and exit the prefab and it has a width of 1 or 15, cutting off the last numbers? It's very annoying

polar acorn
#

Are you looking at the prefab or an instance of it already in the scene? If that instance has overridden those values it won't automatically update to the prefabs values if you change them

#

So, if you made an instance, modified a value, then edited that value on the prefab, the instance won't have that value changed

gaunt cipher
#

no I'm editing the prefab file through double clicking in the assets, its not an instance

oak mountain
#

is it really that bad to store static gameobjects to scriptable objects?

#

I'm trying to make a viewmodel system where it links with my hotbar

#

and what im basically doing is, fetching the itemData from the item in the slot, then seeing what viewmodel prefab its going to use (they are all children in the player's camera) and then it calls my viewmodel manager that handles disabling and enabling the objects correctly

drowsy hearth
oak mountain
drowsy hearth
hushed ridge
#

do you generally make the camera follow the player, or make the player bring the camera to itself?

sour fulcrum
#

generally the former because it's better for the camera to be in charge of it's related responsibility but honestly either is fine

hushed ridge
teal viper
#

reference.variable to access public fields/properties of another object. And "go to it" is basically changing the object position closer to that target position every frame.

#

I'd suggest going over the basics and/or watch some tutorials. Since you're asking very basic questions.

#

!learn

radiant voidBOT
hushed ridge
#

I used too much ai over the summer and need to relearn traditional methods of learning programming 😔

#

i got used to being able to answer niche questions

teal viper
#

These are not really niche questions.
And yeah, I wouldn't recommend using AI if you can't reason about these things with your own head first.

hushed ridge
#

didn't say they were

sand dagger
#

didn't mean to send that so early

#

I'm trying to make a sprint in this basic movement system I'm just messing with, but I'm getting stumped on how to actually make them sprint with the way I have things set up.

Tl;dr I'm using a separate input system and character controller, but all the input system does is just gather the inputs it doesn't have any direct affect on how anything actually works, and for the sake of brevity I've taken everything out that isn't directly relevant.

    private CharacterController _characterController;


    public float walkSpeed = 10f, runSpeed = 20f, RotationSpeed = 5f, JumpForce = 10f, Gravity = -30f;

    void Start()
    {
        _characterController = GetComponent<CharacterController>();
    }

    public void Move(Vector2 movementVector)
    {
        Vector3 move = transform.forward * movementVector.y + transform.right * movementVector.x;
        move = move * walkSpeed * Time.deltaTime;
        _characterController.Move(move);
    }
    
    public void Sprint()
    {
        if(_characterController.isGrounded && Input)
        {
            
        }
    }

The sprint function isn't finished yet, but I'm trying to do is swap the "walkSpeed" with "runSpeed" whenever the player presses the sprint button and I'm using the new input system so I can bind it to the "sprint" action broadly rather than a specific key like the left-shift key. What's most annoying is that I'm pretty sure I've already done something like this in the past but I can't find it and I can't remember how I did it.

wintry quarry
# sand dagger I'm trying to make a sprint in this basic movement system I'm just messing with,...

I'm trying to do is swap the "walkSpeed" with "runSpeed" whenever the player presses the sprint butto
That sounds like a pretty solid approach, and your english sentence here is pretty muhc a fine way to structure it.

Something like:

bool isSprinting = false;
float currentSpeed;
float walkSpeed = 10;
float runSpeed = 20;

public void ToggleSprint() {
  // invert the bool
  isSprinting = !isSprinting;
  // set the speed based on the bool
  currentSpeed = isSprinting ? runSpeed : walkSpeed;
}```
#

then you just call ToggleSprint when the player presses the button

#

unless what you mean is more like "sprint whil ethe button is held down"?

#

Is that what you mean?

sand dagger
#

Yeah while the button is held down

wintry quarry
#

So it will kind of depend on how exactly you're handling the input in code

sour fulcrum
sand dagger
#

My input system looks like this, again irrelevant aspects have been removed for brevity.

    public PlayerController CharacterController;

    private InputAction _moveCommand, _lookCommand, _jumpCommand, _sprintCommand;

    public void Start()
    {
        _moveCommand = InputSystem.actions.FindAction("Move");
        _lookCommand = InputSystem.actions.FindAction("Look");
        _jumpCommand = InputSystem.actions.FindAction("Jump");
        _sprintCommand = InputSystem.actions.FindAction("Sprint");

        _jumpCommand.performed += OnJumpPerformed;
        _sprintCommand.performed += OnSprintPerformed;

        Cursor.visible = false;
    }


    private void OnSprintPerformed(InputAction.CallbackContext context)
    {
        CharacterController.Sprint();
    }
wintry quarry
wintry quarry
#

And setSprinting would just be something like:

public void SetSprinting(bool sprinting) {
  currentSpeed = sprinting ? runSpeed : walkSpeed;
}```
#

(optionally with an internal bool variable if you need to know that info for other things too)

sand dagger
#

And the setSprinting would be in the controller script or the input script

#

Or does it not matter

#

Cause they're both connected anyway

sour fulcrum
#

probably controller

#

they are seperate responsibilities

wintry quarry
#

currentSPeed is a property of the controller, not the input

sand dagger
#

Well I'm not getting any errors but it's also not making me faster

wintry quarry
#

you'd have to show the current state of all your code, as well as inspector defined values, etc

#

also potentially the configuration of the input action

sand dagger
#

InputController

public class InputHandler : MonoBehaviour
{
    public PlayerController CharacterController;

    private InputAction _moveCommand, _lookCommand, _jumpCommand, _sprintCommand;

    public void Start()
    {
        _moveCommand = InputSystem.actions.FindAction("Move");
        _lookCommand = InputSystem.actions.FindAction("Look");
        _jumpCommand = InputSystem.actions.FindAction("Jump");
        _sprintCommand = InputSystem.actions.FindAction("Sprint");

        _jumpCommand.performed += OnJumpPerformed;
        _sprintCommand.performed += OnSprintPerformed;
        _sprintCommand.canceled += OnSprintCanceled;

        Cursor.visible = false;
    }

    public void Update()
    {
        Vector2 movementVector = _moveCommand.ReadValue<Vector2>();
        CharacterController.Move(movementVector);

        Vector2 lookVector = _lookCommand.ReadValue<Vector2>();
        CharacterController.Rotate(lookVector);
    }

    private void OnJumpPerformed(InputAction.CallbackContext context)
    {
        CharacterController.Jump();
    }

    private void OnSprintPerformed(InputAction.CallbackContext context)
    {
        CharacterController.SetSprinting(true);
    }
    private void OnSprintCanceled(InputAction.CallbackContext context)
    {
        CharacterController.SetSprinting(false);
    }
#

CharacterController

public class PlayerController : MonoBehaviour
{
    private CharacterController _characterController;

    private float MovementSpeed;
    public float walkSpeed = 10f, runSpeed = 20f, RotationSpeed = 5f, JumpForce = 10f, Gravity = -30f;

    public float _rotationY;
    private float _verticalVelocity;

    void Start()
    {
        _characterController = GetComponent<CharacterController>();
    }

    public void Move(Vector2 movementVector)
    {
        Vector3 move = transform.forward * movementVector.y + transform.right * movementVector.x;
        move = move * walkSpeed * Time.deltaTime;
        _characterController.Move(move);

        _verticalVelocity = _verticalVelocity + Gravity * Time.deltaTime;
        _characterController.Move(new Vector3(0, _verticalVelocity, 0) * Time.deltaTime);
    }
    
    public void Rotate(Vector2 rotationVector)
    {
        _rotationY += rotationVector.x * RotationSpeed * Time.deltaTime;
        transform.localRotation = Quaternion.Euler(0, _rotationY, 0);
    }

    public void Jump()
    {
        if(_characterController.isGrounded)
        {
            _verticalVelocity = JumpForce;
        }
    }
    public void SetSprinting(bool sprinting) 
    {
        MovementSpeed = sprinting ? runSpeed : walkSpeed;
    }
}
wintry quarry
#

it just directly uses walkSpeed in the Move function

sand dagger
#

That would explain it

#

Okay I swapped it for MovementSpeed but now it isn't moving at all

wintry quarry
#

in Start you should do MovementSpeed = walkSpeed;

#

so it's initialized to walk speed instead of just 0

#

beyond that - make sure SetSprinting is getting called with Debug.Log

sand dagger
#

That fixed it, thank you

#

Everything works now, thank you!

keen dew
real gorge
keen dew
#

The example in the documentation works. If it doesn't work for you, you did something wrong

real gorge
#

I forgot to check out that link i will try it

#
public class DontDestroy : MonoBehaviour
{
    void Awake()
    {
        GameObject[] objs = GameObject.FindGameObjectsWithTag("music");

        if (objs.Length > 1)
        {
            Destroy(this.gameObject);
        }

        DontDestroyOnLoad(this.gameObject);
    }
}

This won't fit my case

silk night
#

what in here doesnt fit your case?

real gorge
silk night
#

FindGameObjectsWithTag just finds all instances, and if there already is one it destroys all further

#

its just the return type of that find function

#

you will only find one (most likely, unless something went wrong)

real gorge
#

Okay maybe I can try that

#

This doesn't work I don't even see how that could work

silk night
#

"This does not work" is not an error description

silk night
real gorge
#

Okay i managed to make it work:

using UnityEngine;

public class DontDestroy : MonoBehaviour
{
    public GameObject[] objs;
    void Awake()
    {
        if (objs.Length > 0)
        {
            Destroy(this.gameObject);
        }

        DontDestroyOnLoad(this.gameObject);
    }
}
#

It doesn't work on cameras tho

verbal dome
#

What even happens if you DDOL an object that is also being Destroyed 🤔

naive pawn
verbal dome
#

Probably just destroys fine?

naive pawn
#

DDOL just moves it to a different scene, no? stuff in there can get destroyed just fine

#

and Destroy works after a frame, so i don't think DDOL would end up targetting a destroyed object

#

if it were DestroyImmediate, that could have issues though

verbal dome
naive pawn
#

what even is this

real gorge
naive pawn
#

a bastardized singleton? lol

verbal dome
real gorge
naive pawn
verbal dome
#

Ah yeah that has a DDOL example^

real gorge
#
using UnityEngine;

public class DontDestroy : MonoBehaviour
{
    private static DontDestroy _instance;
    void Awake()
    {
        if(_instance !=  null)
        {
            Destroy(gameObject);
        }
        else
        {
            _instance = this;
            DontDestroyOnLoad(gameObject);
        }
    }
}

This would work if I made separate script for every object i want to keep

naive pawn
#

yes, that's typically how the singleton pattern goes

#

if you have like, 10+ objects you want to keep, you might just.. have too many

sour adder
#

But you have no content in your class, if you want the camera to not destroy you better include it in your class.

real gorge
#

I will just add this part to camera and ui class

naive pawn
#

stuff is a singleton, not has a singleton

real gorge
#

i mean implement*

#

DontDestroyOnLoad doesn't apply to object's children?

verbal dome
#

It does

#

So no you don't need to 'include the camera in your class'

real gorge
verbal dome
#

Do they also have some script that sets them DDOL?

#

Because DDOL should be only used on the root object

real gorge
naive pawn
#

what is going on there..

verbal dome
naive pawn
real gorge
verbal dome
#

Then you have some script destroying them

real gorge
naive pawn
#

your DontDestroy has one...

verbal dome
#

And you used the search feature to confirm that they really are being destroyed?

verbal dome
naive pawn
verbal dome
#

They didn't really ask for a specific singleton, just DDOL

naive pawn
#

they're using the singleton pattern in their DontDestroy, and given that this is not in a persistent additive scene, you'd need a set in each scene for ease of testing

#

it's already a singleton, just not a particularly useful one

#

it's in the actual class of the camera controller, rather than some generic DontDestroy class, right?

naive pawn
#

could you be more specific as to how it isn't working for the other one?

real gorge
#

When i start the game I have both Free Camera an DebugUi. When I switch scenes only Free Camera is present on the new scene

naive pawn
#

it shouldnt actually be in the scene

#

it should be in the DDOL scene

real gorge
#

But it's not

naive pawn
#

these gameobjects are active, right? also make sure you've saved and recompiled

real gorge
#

I will show screenshots

naive pawn
#

could you show the hierarchy as you switch scenes

real gorge
#

In editor

#

Scene 1 (Playing)

#

Scene 2 (Playing; Switched from Scene 1)

naive pawn
#

FreeCamera and DebugUi are on Free Camera and UI?

real gorge
#

yes

naive pawn
#

neither appear to be in DDOL there

real gorge
#

And now the free cam also doesn't work!

real gorge
naive pawn
#

do you have domain reload disabled

real gorge
#

Oh i accidently moved the code files to downloads when i wanted to put on discord instead of copying

naive pawn
#

wonderful

#

for future reference

#

!code

radiant voidBOT
real gorge
#

Okay everything now works. I created two scripts FreeCameraDdol and UiDdol with private void Awake() { if (_instance) { Destroy(gameObject); return; } DontDestroyOnLoad(gameObject); _instance = this; }

burnt vapor
#

While it won't have much difference here since Unity has custom behavior it never works for other non-Unity classes unless they do the same

real gorge
burnt vapor
#

If this took 2 hours of work then it might be better to get more familiar with Unity and/or learn what makes this code work

burnt vapor
#

Make sure you actually get rid of the instance when switching scenes so the debug UI can reinitialize. Otherwise it's dangling against a component that no longer exists

real gorge
#

Maybe I need to fix something with listeners

burnt vapor
#

At least, I assume your Debug UI exists in both scenes?

#

And you DDOL the first one?

real gorge
burnt vapor
#

Does your other scene have the same UI?

real gorge
#

No i have DDOL script. The UI object is only in the first scene (main scene)

burnt vapor
#

Do you have an event system in the new scene?

real gorge
#

I do

pallid lynx
#

i got this warning so i changed the relevant line to awake but it still flagging as an error:

    void Awake()
    {
        player = GameObject.FindGameObjectWithTag("Player");
        rb = player.GetComponent<Rigidbody>();
    }
#

why is this happening?

naive pawn
#

make sure you've saved and recompiled

pallid lynx
#

i have

verbal dome
#

Did you remove FindGameObjectWithTag from where you were previously using it

naive pawn
#

also go down the stacktrace, see if it's actually from this script on that line

pallid lynx
# verbal dome Did you remove FindGameObjectWithTag from where you were previously using it

public class GrapplePointInteractable : MonoBehaviour, IInteractable
{
    GameObject player;
    Rigidbody rb;

    void Awake()
    {
        player = GameObject.FindGameObjectWithTag("Player");
        rb = player.GetComponent<Rigidbody>();
    }

    void Start()
    {
        
    }

    public void OnClick()
    {
        Debug.Log(transform.position);
        rb.MovePosition(Vector3.up*20);
    }

    public void OnDrag(Vector3 hitPoint)
    {
        //throw new System.NotImplementedException();
    }

    public void OnDragEnd()
    {
        //throw new System.NotImplementedException();
    }

    public void OnDragStart(Vector3 hitPoint)
    {
        //throw new System.NotImplementedException();
    }

    public void OnHoverEnter()
    {
        //throw new System.NotImplementedException();
    }

    public void OnHoverExit()
    {
        //throw new System.NotImplementedException();
    }

    // Start is called once before the first execution of Update after the MonoBehaviour is created


    // Update is called once per frame
    void Update()
    {
        
    }
}
``` i did
pallid lynx
naive pawn
#

does the stacktrace not have more content?

pallid lynx
#
UnityException: FindGameObjectWithTag is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'GrapplePointInteractable' on game object 'Sphere'.
See "Script Serialization" page in the Unity Manual for further details.
UnityEngine.GameObject.FindGameObjectWithTag (System.String tag) (at <31f3cd5c2a074982a9d5664e7709cac1>:0)
GrapplePointInteractable..ctor () (at Assets/Scripts/GrapplePointInteractable.cs:5)

naive pawn
#

GrapplePointInteractable.cs:5

#

the :5 means line 5

pallid lynx
#

ah

verbal dome
#

Maybe you just didn't clear previous errors in the console?

pallid lynx
#

perhaps

#

._.

verbal dome
#

Check if you have Clear on recompile disabled

pallid lynx
#

it was indeed disabled

#

only now i realize the starter asset 1st person controller doesnt have a rigid body -_-

#

oh well, ill experiment with Translate

verbal dome
#

Does it have a CharacterController?

#

If yes you should use that to move it

pallid lynx
#

oh ok

verbal dome
#

cc.Move

pallid lynx
#

i'm still not entirely familiar with what CharacterController does or can do, so thanks

#

i wanted to access the Grounded bool from the script, since it was already public, but im not sure what the correct syntax or function to do it is

naive pawn
#

you have to type it properly first

pallid lynx
#

i tried that but it shows this

naive pawn
#

you've typed it just as a MonoBehaviour

pallid lynx
#

oh ok

naive pawn
#

MonoBehaviours don't have all that extra stuff

pallid lynx
#

that makes sense

#

it's not quite having the inteded effect, probably being overridden by the firstpersonController script -_-

#

i wanted to disable the effect of gravity while clicking an object in the world

#

maybe i could change Gravity instead of grounded

naive pawn
#

...you were trying to change the grounded state?

pallid lynx
#

i'm trying to make a grapple point you hold and it pulls you towards it

#

i got the pulling working, but gravity still affects you during it

#

so i was trying to make the player "grounded" at that time

naive pawn
#

if you wanted to disable gravity, then disable gravity, not some weird other thing

pallid lynx
#

well, disabling gravity didnt really work either, mostly my interactibility scripts fault

naive pawn
#

cool, then ask about that

#

being grounded typically does not disable gravity

verbal dome
#

Many controllers disable gravity when grounded to avoid sliding down hill when not moving

#

(Not sure how relevant that is with CC though)

naive pawn
#

that would make the CC handle incorrectly though

verbal dome
#

Right because it expects the gravity to push it into the ground in order to detect being grounded?

naive pawn
#

yes

verbal dome
#

Just seems like this script is doing its own ground checks (I see GroundedRadius etc)

pallid lynx
#

this is a world object intereaction script i made for the camera,
the issue is that the dragging action doesnt end when the mouse is off the object, so if i'm still holding when i look away the drag wont end, and gravity wont be reset

naive pawn
#

!code

radiant voidBOT
pallid lynx
#

i know about inline

naive pawn
#

you weren't supposed to post it inline

#

read the "large code blocks" section

pallid lynx
#

oh i see

#

do i paste the link after putting the code in the site?

naive pawn
#

yes

pallid lynx
naive pawn
#

so you aren't receiving any input whatsoever when the mouse is not on an object
consider handling the cancel/complete actions outside the raycast check

i'm also noticing that if you drag from nothing onto an object and release, it seems that you'd call OnDrag/OnDragEnd on that object

pallid lynx
#

so pass the endDrag if to otuside the physics raycast main if?

#

lemme try

#

wait no that doesnt work

#

cause that returns a null if you arent pointing at anythin

naive pawn
#

you'd be targetting currentInteractable

#

tbh you should probably be targetting currentInteractable for some other of those too

#

just makes more sense as you read it

pallid lynx
#

i'm a bit lost, nothing works outside the main raycast checks since both currentInteractable and newInteractable remain null, unless you mean to check currentInteractable in the raycast if check

ancient nimbus
#

does anyone know how to smooth out a vector 3?

PlayerRigidBody.linearVelocity = new Vector3(MoveDir.x, PlayerRigidBody.linearVelocity.y, MoveDir.y);

wintry quarry
ancient nimbus
wintry quarry
#

It sounds like what you mean is "smooth out the transition from the current velocity to the user's input velocity"

ancient nimbus
#

yup

wintry quarry
#

you could do something simple in FixedUpdate like use the MoveTowards function to make the transition gradual. But you'll want to make sure the y part is not including. Something like:

float acceleration = 5f;

void FixedUpdate() {
  // what's the current velocity?
  Vector3 existingVelocity = PlayerRigidBody.linearVelocity;
  float yVel = existingVelocity.y;

  // Establish our target velocity
  Vector3 targetVelocity = new(MoveDir.x, yVel, MoveDir.y);

  // do the smoothing
  Vector3 newVelocity = Vector3.MoveTowards(existingVelocity, targetVelocity, acceleration * Time.deltaTime);

  PlayerRigidBody.linearVelocity = newVelocity;
}```
ancient nimbus
wintry quarry
#

FixedUpdate is in cadence with the physics engine

#

which is what matters here because the velocity is only used to move the player in the physics update

#

Update runs every single frame

wintry quarry
#

the diagrams in there explain it really well

ancient nimbus
astral ice
#

can i talk about visual scripting here too or not

sour fulcrum
dark hatch
#

hi i was looking for a way to slowly rotate an object towards another in 2d. basically i have a missile that i want to aim towards a moving target but i cannot use quaternion.slerp because the missile is constantly changing position as well as the target. i probably need to rotate a vector towards another vector with time, but im not sure how to do that without slerp because slerp i can only really use when vectors are actually fixed

#

alternatively i could just rotate it clockwise/anticlockwise until the difference in angle is very small but i was wondering if there was some simple solution im missing out on

wintry quarry
#

As does Vector3.RotateTowards

#

Slerp can still work it's just not recommended

#

YOu can also use angular velocity if it's a rigidbody

dark hatch
#

that does sound almost perfect for me

wintry quarry
#

even 2d games

#

but basically you would just be dealing with transform.right

dark hatch
#

yeah

wintry quarry
#

e.g.

transform.right = Vector3.RotateTowards(transform.right, directionToTarget, Time.deltaTime * rotateSpeed, 0);```
dark hatch
#

i was trying to avoid using transform.right/left/up etc. cuz it confused me

wintry quarry
#

it's the simplest way for sure

dark hatch
#

okay

wintry quarry
#

transform.right is just the red arrow in the scene view

#

"rotate my red arrow towards directionToTarget"

dark hatch
#

and transform up must be the blue?

wintry quarry
#

think of it that way

wintry quarry
dark hatch
#

okay

wintry quarry
#

transform.forward is the blue

dark hatch
#

i see

#

alright

#

let me try it

wintry quarry
#

(whether to use up or right depends on how your sprite image is laid out)

dark hatch
#

im just using a square bullet stretched on x-axis so i guess transform right should make it look correct

wintry quarry
#

make sure directionToTarget is calculated properly as well

#

it would be:

Vector3 directionToTarget = target.position - transform.position;``` assuming `transform` is the projectile
#

Make sure you're at the same z position as well

#

if not you'd need to 0 it out: directionToTarget.z = 0;

dark hatch
#

yeah i already ran into the z-axis problem and fixed it i was just stumped on the rotation

tribal schooner
#

Hi, anyone try to putting a animation by script like that?

#

I was trying to playing a animation via script to make a live, when losted, start a animation

#

But I'm don't know its schizophrenic from my part, or it's realy possible to do this

sour fulcrum
#

!code

radiant voidBOT
swift crag
#

most of that is correct, but this is not:

#
var _lostLifeHash = lostLifeClip.GetHashCode();

GetHashCode() is completely unrelated to the concept of a "hash" in the animator

#

every C# object can give you a hash code, and the hash code is meant to be used for things like testing if two objects are the same thing

#

You want this method:

#

StringToHash is useful if you're going to play an animation many times. It reduces the amount of work needed to find the correct animator state

#

I wouldn't bother here, since you're only doing it once

tribal schooner
#

I'm forgot the string to hash exist haha

#

Thanks

foggy lance
#

using System;
using UnityEngine;

public class ChestSystem : MonoBehaviour
{
void ChestOpened()
{
// Save the expiration time when the chest is opened
DateTime expireTime = DateTime.UtcNow.AddMinutes(50);
PlayerPrefs.SetString("ChestExpire", expireTime.ToString("o"));
PlayerPrefs.Save();
}

void OnGameEntered()
{
    string saved = PlayerPrefs.GetString("ChestExpire", "");

    if (string.IsNullOrEmpty(saved)) return;

    DateTime expireTime = DateTime.Parse(saved);
    TimeSpan remainingTime = expireTime - DateTime.UtcNow;

    if (remainingTime.TotalSeconds <= 0)
    {
        Debug.Log("Chest is ready! You can open it.");
    }
    else
    {
        Debug.Log($"Time remaining: {remainingTime.Minutes} minutes {remainingTime.Seconds} seconds");
    }
}

}

#

this code work right ?

polar acorn
#

Also,

#

!code

radiant voidBOT
brittle carbon
#

hi!!! i am beginner and how do i start learning C#?

solar hill
#

check the pins here

#

there are a few guides to get you started

radiant voidBOT
solar hill
#

👆 this is for my unity oriented stuff

brittle carbon
#

wdym?

#

like i cant find any good tutorial on yt

#

is there any site where they teach everythin from basics?

polar acorn
#

You've been given several

rich adder
#

and the Unity learn site for unity specific, but you should go through basics of c# beforehand

brittle carbon
#

thanks i will try it

vast matrix
#

I am trying to code a support Enemy that boosts the Enemies around it. How would I apply the boosts to the enemies around it? I can't seem to figure out how

lofty sequoia
#

what's the point of dynamic font atlas for textmeshpro fonts?

rich adder
#

what exactly are you trying to boost anyway ?
movement? health ?

vast matrix
naive pawn
rich adder
vast matrix
#

How would I get the information of all the enemies in range and apply the buffs? I tried GetComponent but that doesn't work for 2+ enemies since it only grabs the script from a single enemy.

rich adder
#

probably less efficient , if without collider those you need a way to register enemies in some sort of tracker / list and youd have to compare distances at certain intervals and if they are within range you'd apply/remove the buff

#

Overlap would for example give you an array of enemies within a zone then you can loop through those and apply it

sour fulcrum
#

i feel like we could make a nice little visual guide on the ways you communicate between things

frail hawk
#

i´d also recommend using overlap all the way

rich adder
#

overlay is good but you'd need a way to tell if they left the zone if they entered one

#

TriggerEnter/Exit may be easier for a beginner

#

Enters Trigger -apply buff
exit Trigger - remove buff

vast matrix
#

I've never heard of Overlay before. I'm going to do research into it.

lofty sequoia
#

there now it's a code question

vast matrix
frail hawk
#

overlapsphere is what you need

vast matrix
#

Oh thank you.

rich adder
#

for optimization purpose the NonAlloc version is better

#

remember Overlap will only tell you whats inside RIGHT NOW

naive pawn
rich adder
#

pretty simple to do check though, you can keep the colliders tracked inside a HashSet then compare at the end of the frame

vast matrix
#

After I know whether the Enemies are inside or outside the radius how would the buff be given to them?

rich adder
#

you can either do it through a method that modifies the stats you want, or maybe apply a specific component for buffs.. really depends on the design

frail hawk
#

unityevent could be really helpfull, you invoke the event and all the enemies that are nearby get informed

vast matrix
#

I honestly forgot UnityEvent existed

rich adder
#

could also work yeah you just need to consider how many things can apply those sorts of buffs

lofty sequoia
#

The only fix I've found for this is to paste into a textbox that uses the font a text file with all characters you will use (alphabet/num/sym) and then set it to static. Otherwise you get artifacts like a single letter in a word using the fallback text.

frail hawk
#

as nav said, there are really many ways of doing this

gilded badge
#

You quick question: my and two friends are working on a game for school and it is my task to figure out how to store general data while the game is running. We have a post void-like game and we need to store in what level the player is, and how long the current level should be, the score of the player and those things. How do we simply store those? The data doesn't have to be stored if the game is closed.

lofty sequoia
#

It would be nice if setting to static gave you a default working set of symbols

sour fulcrum
#

Both ! 😛

gilded badge
#

I only need one

rich adder
#

either will work (since this isn't a permanent save anyway)

frail hawk
#

i´d simply use a static non MonoBehaviour for this

rich adder
#

that could work too

frail hawk
#

orr a singleton could also do the job

sour fulcrum
rich adder
#

after all SOs are very similar to how static class works (data itself per SO)

sour fulcrum
#

im scriptable singleton pilled now

gilded badge
sour fulcrum
#

thats a good requirement

gilded badge
#

and maybe that it doesnt cause my game to crash

#

since the deadline is tomorrow and we procrastinated a fuck ton

rich adder
#

thats vague . all the mentioned methods *just work *™

sour fulcrum
#

google dontdestroyonload singleton

#

youll probably get somewhere

rich adder
frail hawk
#

i think someone needs to spoonfeed that dude he is in a hurry

sour fulcrum
#

people in a hurry can starve then 😛

sour fulcrum
gilded badge
#

is it just making a background scene with a script attached that stores the data>

sour fulcrum
#

just open the link homie

gilded badge
#

alright big boi

rich adder
sour fulcrum
#

generally the pattern i use just checks if the field is null and if it is assigns it

#

so it is a null check per reference fair

#

i guess you could use a bool though idk

#

awake just feels a little flimsy, maybe its a skill issue on my behalf

gilded badge
#

so I make the singleton class with the variables and maybe a method or two, and when I need it in a class I just make that class inherit the singleton?

#

can it inherit both singleton and monobehaviour at once?

sour fulcrum
#

no

#

you have 1 class inheriting the singleton

rich adder
#

thats if you create a generic

sour fulcrum
#

and put your info in there

#

and then you can access the singleton from anywhere

rich adder
#

which code block are you looking at. @gilded badge

gilded badge
#

the last two

#

no wait the first two

#

i am now looking at the last two

rich adder
#

yes if you use the second pattern then you would put the public fields you want / method in the child class

#

thats if you want to make multiple singletons without having to keep writing the same pattern for each (we avoid repeating code as much as possible for clean code)

gilded badge
#

I think i just need one?

rich adder
#

if I were you I'd make a struct for that data you want then put that in the singleton

[Serializable]
public struct LevelData {
public int Score;
public int Level;
}

public class MySingleton : MonoBehaviour {
public LevelData LevelData = new();
//awake setup
...

MySingleton.Instance.LevelData.Score = 32
etc.

gilded badge
#

so I do
Singleton.cs

public abstract class Singleton<T> : MonoBehaviour
    where T : Singleton<T>
{
    public static T Instance { get; private set; }

    void Awake() 
    {
        // Destroy this object if we already have a Singleton defined
        if (Instance != null)
        {
            Destroy(gameObject);
            return;
        }
        DontDestroyOnLoad(gameObject);
        Instance = (T) this;
        DoAwake();
    }

    // Virtual method to allow implementations to use Awake
    protected virtual void DoAwake () { }
}

public class YooooooData : Singleton<Foo>
{
    double score = 0;
    int iterationlength = 12;
}

dosomestuff.cs

using UnityEngine

class DoSomeStuff : Monobehaviour 
{
  void Start()
  {
    Debug.Log($"hey look data {YooooooData.Instance.score}");
  }
}
sour fulcrum
#

YooooooData.Instance.score

gilded badge
#

oops

sour fulcrum
#

statics are weird to learn at first its no stress

#

but yeah

#

try it out

gilded badge
#

alright

#

I will

#

if it goes wrong im blaming yall /j

rich adder
#

I'd still recommend storing some stuff in a saperate POCO if you later decide to save it in a file

solar hill
sour fulcrum
#

this isn't advice for bread person but just on the topic of singletons i've really been liking this

public class ScriptableManager : ScriptableObject
{
    private static ScriptableManager _instance;
    public static ScriptableManager Instance
    {
        get
        {
            if (_instance == null)
                _instance = Resources.LoadAll<ScriptableManager>(string.Empty)[0];
            return (_instance);
        }
    }

having singletons as scriptableobjects has been super helpful in not having to rely on a given scene having to be loaded up and/or cursed editor code to redirect scene loading and stuff

rich adder
#

(string.Empty)[0];
this means you have to use Resources folder and hope its the first one is the proper SO?

sour fulcrum
#

ye

#

i figure its about the same level of an assumption as a mono

gilded badge
rich adder
gilded badge
sour fulcrum
#

fair

#

its the only thing i ever use resources for

rich adder
#

Yeah i used to use Resources but switched to Addressable if needed
(not this usecase specifically tho so it doesn't matter in the long run )

sour fulcrum
#

i was pondering if it was possible to use a little editor script to create and assign an instance of a scriptablesingleton to the actual monoscript and if that worked as a reference to an asset for builds

#

very cursed option so haven't tried it

rich adder
#

oh me I'd use any excuse to try making editor script xD sometimes I enjoy it more than coding in unitygame itself

gilded badge
#

as a javascript and typescript soydev, I am glad to see arrow functions in C# because they are just so clean if an entire function body is one return statement

sour fulcrum
#

oh absolutely but im sick of being unemployed so i gotta actually make games 😭

solar hill
rich adder
#

exactly

solar hill
#

i was so lazy to fix some animations in blender i created an editor script that lets me apply offsets all at once across keyframes

sour fulcrum
#

look at this before and after cleanup of this inspector 😄

#

way too much time spent on this

#

never got used !

#

so much time on unused tooling

rich adder
#

I have a bunch of those but I look back and rather have something pleasant to look at later on lol

gilded badge
#

Okay it doesn't work

#

the singleton

rich adder
#

ok so what did you do to test and whats the result

gilded badge
#
// Sla hier global data op
using UnityEngine;

public abstract class Singleton<T> : MonoBehaviour
    where T : Singleton<T>
{
    public static T Instance { get; private set; }

    void Awake()
    {
        // Destroy this object if we already have a Singleton defined
        if (Instance != null)
        {
            Destroy(gameObject);
            return;
        }
        DontDestroyOnLoad(gameObject);
        Instance = (T)this;
        DoAwake();
    }

    // Virtual method to allow implementations to use Awake
    protected virtual void DoAwake() { }
}

public class ContextData : Singleton<ContextData>
{
    public double score = 0;
    public float mapSize = 6;
}
using System;
using Unity.AI.Navigation;
using Unity.Mathematics;
using UnityEngine;
using static Utils;

public class GenMan : MonoBehaviour
{
    readonly int iterations = Convert.ToInt32(math.floor(ContextData.Instance.mapSize));
    Vector3 currentCoordinate = new(0, 0, 10);

    int currentAngle = 0;

    [SerializeField]
    private GameObject straightHallSegment;

    [SerializeField]
    private GameObject leftTurnHallSegment;

    [SerializeField]
    private GameObject rightTurnHallSegment;

    [SerializeField]
    private GameObject startRoomSegment;

    [SerializeField]
    private GameObject endRoomSegment;

    private NavMeshSurface surface;

    // Sanity check :D
    void Awake()
    {
        if (iterations < 6)
            Debug.LogError($"invalud iteration: {ContextData.Instance.mapSize}");
        // unimportant
    }

    void Start()
    {
        // unimportant    
    }
}
#

this is the error

rich adder
#

if you're getting a null reference its most likely because you're trying to call this in awake before the other awake ran

wintry quarry
rich adder
#

you can change the script order or access singleton in start

gilded badge
sour fulcrum
wintry quarry
gilded badge
#

thats seems logical

wintry quarry
#

that's especially bad

#

trying to access it in a field initializer like that isn't gonna work

gilded badge
#

so I think I should call the ContextData.Awake() somewhere?

rich adder
wintry quarry
#

iterations I would probably make a property so it's lazy loaded

sour fulcrum
wintry quarry
#

Move your sanity check into Start not Awake

gilded badge
#

and merge it with the other start? sure

#

explain

rich adder
#

Singleton setup Awake
Other Scripts access that singleton Start

#

otherwise you need to change the script execution order

sour fulcrum
#

your trying to walk into a store before they are open

gilded badge
rich adder
#

you're trying to poo before the toilet seat cover has been open 🤔

gilded badge
#

omg i get it

sour fulcrum
#

your trying to enter the last judge fight without ringing the bells

gilded badge
rich adder
gilded badge
sour fulcrum
#

right now the code is running

GenMan.Awake()
ContextData.Awake()

#

you want the stuff in genman.awake to happen after contextdata.awake

gilded badge
sour fulcrum
#

awake then start

#

just use start in genman instead of awake

rich adder
sour fulcrum
#

dats it

gilded badge
rich adder
#

when you do
Script1.Awake()
Script2.Awake()
its not guaranteed which one will run first unless you messed with execution order

gilded badge
#

okay ill test now

rich adder
#

so usually ppl do
Script1.Awake()//Setup
Script2.Start() // usage

gilded badge
#

okay so i put the sanity checkin start, genman doesnt have an awake method now but it still doesnt work

rich adder
#

you have to be more specific

gilded badge
#

okay the same error persists

sour fulcrum
#

is there a contextdata component in the scene

rich adder
#

put Debug.Log inside ContextData Awake and see if it runs

gilded badge
sour fulcrum
#

ah i guess that was a lost assumption

rich adder
#

MB need to be on gameobjects to run

sour fulcrum
#

its not in the tutorial page so honestly fair

#

you just gotta stick it on a empty object

rich adder
#

its kinda unity 101 stuff lol

gilded badge
sour fulcrum
#

ehhh your not wrong but with the statics and generics it might get lost in the sauce

gilded badge
gilded badge
gilded badge
rich adder
rich adder
#

the Awake in ContextData you put isn't running because it should tell you its running the one from parent

#

"something something hides inherited member.."

gilded badge
#

do i do that in the script or in the editor?

sour fulcrum
#

you add it to a gameobject

#

in the scene

gilded badge
#

oh

rich adder
#

GameObjects -> Containers of components basically
MonoBehaviours -> Components

gilded badge
rich adder
#

Ideally on its own Gameobject with the same name so its easy to find but it doesnt matter where, as long as you remember where it is

gilded badge
#

alright

rich adder
#

especially if its a DDOL you may not want GenMan to be carried too

gilded badge
#

im confused

#

when i click "add component" "contextdata" isnt there

sour fulcrum
#

oh

#

for monobehaviours, 1 file per class definition

gilded badge
#

i have that

sour fulcrum
#

you have two

#

Singleton<T> and ContextData need a .cs each

rich adder
#

ContextData.cs should be its own file

gilded badge
#

alright, lemme do that

#

Did that

#

What now

sour fulcrum
#

now you should be able to add component

gilded badge
#

yay its there

#

now it says that there is a NullReferenceException at GenMan.cs, which is this readonly int iterations = Convert.ToInt32(math.floor(ContextData.Instance.mapSize));

#

Im guessing its because awake hasn't been called or something?

slender nymph
#

yes, you'd (ideally) want to wait until Start or later to access the singleton, and a field initializer runs before even Awake does for that object

gilded badge
#

okay so how do we make it wait

sour fulcrum
#

iterations = Convert.ToInt32(math.floor(ContextData.Instance.mapSize));
put this in start

rich adder
#

didn't we tell you this earlier a few times

slender nymph
gilded badge
rich adder
#

ask for clarification then

slender nymph
#

here's another rule of thumb: if you don't understand something then ask for clarification instead of ignoring the things people tell you

gilded badge
#

alright, thats true, my fault

#

I apolagize

#

Okay it works now yippie :D

#

Okay so for context when i reach the end of my level, you dive inside a swimming pool whose walls are made of gruyere cheese (long story), which increases the level lenght (which is what i needed the contextdata for), and then reloads the current scene so you start at the beginning again and clear the slightly longer level again

#

problem: when the scene is reloaded, the map doesn't generate (which means the contextdata isnt delivered properly somehow)

rich adder
#

cause that causes that object not to be destroyed on reload

gilded badge
#

what is DDOL?

gilded badge
rich adder
gilded badge
#

aha

rich adder
#

that was to keep the values "saved" between reloads

#

the object wont run awake / start again in that case

gilded badge
#

aha, so the reload script looks like this:

using UnityEngine;
using UnityEngine.SceneManagement;

public class EndLevel : MonoBehaviour
{
    void OnTriggerEnter(Collider other)
    {
        Debug.Log("Level cleared");
        SceneManager.LoadScene("Game", LoadSceneMode.Single);
        ContextData.Instance.mapSize *= 1.2f;
    }
}
sour fulcrum
#

dont you want to set map size before you load the scene?

gilded badge
#

yes, lemme swap order

rich adder
#

maybe im wrong nvm just swap the order just incase

sour fulcrum
#

i don't think so?

#

i also could be wrong

#

pretty sure that will at least pop awakes on the new scene before getting to mapsize

gilded badge
#

can I put the contextdata on a different gameobject and then access that?

sour fulcrum
#

you have no reason to do that

rich adder
#

contextdata should be on its own object if you dont want other objects to DDOL

gilded badge
rich adder
#

DDOL will keep the gameobject "alive" do you want MapGen to also not reload awake/start

gilded badge
#

i do want it to restart so it generates the map again?

rich adder
#

so then dont put it on the same contextdata object because its set as DDOL

gilded badge
#

yes

rich adder
#

DDOL = dont destroy this gameobject between reloads / scene changes

rich adder
#

I did say this earlier, yes its should ideally be its own gameobject

gilded badge
#

alrihgt let me do that

rich adder
quick tundra
#

for some reason my dropdown doesnt remove the checkmarks of previous selections?

#

i dont have multi select on, so im confused on why this is the case

teal viper
quick tundra
#

just clicking

teal viper
#

And that's after unchecking the multi select?

quick tundra
#

yep

teal viper
#

Does it stay unchecked at runtime?

quick tundra
#

yep

teal viper
#

Can you take a screenshot of the whole component?

quick tundra
#

code:

#
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class DifficultySelect : MonoBehaviour
{
    [SerializeField] TMP_Dropdown dropdown;
    void Start()
    { 
        dropdown.value = GameManager.instance.difficulty;
        dropdown.onValueChanged.AddListener(ValueChanged);
    }
    void ValueChanged(int index)
    {
        GameManager.instance.SetDifficulty(dropdown.value);
    }
}
teal viper
#

Oh, it's the tmpro one...

quick tundra
#

lol glad im not the only one that groans when i see that

#

welp no clue what i did

#

but now it works

#

LOL

#

average unity bug ig

teal viper
#

Yeah, tmpro components aren't documentes very well beyond the regular text components.

#

There isn't even an explanation of that property anywhere.

sour fulcrum
#

    private void InitializeGame()
    {
        GameObject navMeshSurface = new GameObject("NavMeshSurface");
        DontDestroyOnLoad(navMeshSurface);
        surface = navMeshSurface.AddComponent<NavMeshSurface>();
        surface.layerMask = navMeshMask;
        surface.BuildNavMesh();
        Debug.Log("Meow Meowed");
    }

before i get too deep into debugging this any guesses on why the navmesh seemingly fails to generate nicely in builds but is fine in editor? the log runs and theres no meshes to cause r/w issues

sour fulcrum
#

solved, was popping off from
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
in build i needed
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]

muted sand
#

How do i get out of tutorial hell?
I've been through it before it just seems a bit slow because I have less and less time overtime
e.g. making a basic movement system for an FPS game, what's the best way to do that?
*I have proficiency in lua(u) because of other game development engines

sour fulcrum
#

there is no best way

#

there's honestly a million ways

#

best way to get out of tutorial hell is to slowly learn how to learn so instead of relying on strict tutorials you can figure out which specific parts of code and/or unity you don't understand so you can learn that part individually and put them together like puzzle pieces

muted sand
#

i read API alot but i wanted to speed up the process

#

because i would've saved alot of time if i just found out about a peculiar one

sour fulcrum
#

it's easy to find a movement system for a fps game, even unity hub has some templates and tutorials directly

#

pick that and work with it 😛

muted sand
#

tanks

sour fulcrum
muted sand
waxen adder
#

Got a code philosophy question. Which is better? Having a singular script involved in all things player movement, or a bunch of smaller scripts for individual actions?

keen dew
waxen adder
fading spade
#

can player movement be restricted for some reason

#

if yes, smaller scripts might be better

waxen adder
#

I guess here's one example rolling around in my head. What if an item gives a new movement option exclusive to it?

fading spade
#

it would be easier to just attach a component

#

rather than do an if else in one big script

#

as long as you don't have 8 billion movement options, the resource cost is inconsequential

waxen adder
#

So in that situation multiple smaller scripts would be the approach?

fading spade
#

yeah

#

each item can add or remove components when given, taken respectively

waxen adder
#

Gotcha. I imagine if it was something where your movement options remain static, then one big script would be fine

fading spade
#

yeah

#

pretty much

waxen adder
fading spade
#

you wouldn't need multiple components when every movement behaviour is clearly identified

rich adder
fading spade
#

scripts

#

like additional update calls and input checks

waxen adder
#

Gotcha. I think I have a better picture here

fading spade
#

is there a good way to serialise stat modifiers that modify arbitrary stats

rich adder
#

so like don't put inputs in a movement script cause now you're limited by Player controlled movement and now you need to make a separate script for enemy, when you can just keep the same script but pass inputs via method so only player requires "input capture component"

waxen adder
#

Ah, yeah I got something like that right now. A component dedicated to input capture

fading spade
#

rn i'm thinking generating a dictionary with reflection on awake so i can just index things, but it feels wrong almost

rich adder
#

dont you have like an enum or something more reliable than a bunch of brittle strings to match ?

fading spade
#

if you have a few dozen stats you need a enum with a few dozen entries

rich adder
#

how so ?

fading spade
#

and how would it be referenced in a json

rich adder
#

how many stats you gonna have

#

the ussuals ?
public enum StatType{
Attack,
Defense,
Speed,
CritChance
}

fading spade
#

there's around 10 so far

rich adder
fading spade
#

i'd also want to open it up for modding

fading spade
rich adder
#

in json but not in your game logic

fading spade
#

i don't reckon the dictionary will be used during game time,
it'll just be used when loading a character to switch all the "stat" strings in json to an object reference

rich adder
#

all you gonna do is get the json stuff and convert to object, the rest is handled in like a dictionary

rich adder
#

enums are def closed

fading spade
#

figured

#

should be fine if i don't use the dictionary outside of loading the character?

rich adder
#

wdym why whats wrong with dictionaries

#

dictionary is common in modds

#

I meant with strictly reflection only and not implementing a more structured thing to fallback on
but how much you gonna give leeway that wont just break your game lol

fading spade
#

there's not really any point of using the dictionary afterwards? unless it's a stat that's modded in then yeah

rich adder
#

it still gets hashed afaik

fading spade
#

also avoids magic string in the code

#

something like this for class fields

Stat stat
Stat anotherStat
dictionary<string, Stat> statIndex

All vanilla code will use stat and anotherStat directly, mods will have to resort to the dictionary to access the stats

#

stat, anotherstat are also kept in statIndex

rich adder
#

as long as they're the same I suppose

#

or might be a duplication bug

fading spade
#

when an character gains an item
{"stat": "anotherStat", "value": 5} creates a modifier class instance with a reference to the anotherStat object from character, and value of 5

fading spade
fading spade
#

something like this effectively

burnt vapor
#

I don't know the logic your mod has so I can only assume things but generally these are not the things that will cause performance issues

fading spade
#

Fair

#

Still nice to not have to use magic strings everywhere

fleet ivy
#

Is there an equivalent of OnPointerDown/Up but for gamepad face buttons?

wintry quarry
#

Do you mean when using UI navigation? Or do you mean when using a virtual cursor

#

Or do you not mean UI at all

fleet ivy
#

UI navigation on a button

wintry quarry
#

You need to provide more details about the situation

#

There's OnSubmit if you're hitting the submit button

#

ISubmitHandler

fleet ivy
#

I need to be able to hold down the south face button on a controller to press a button, not just pressing it

wintry quarry
#

Are you using the new input system or old

fleet ivy
#

Also progress a progression bar so I need to know when the button is first pressed and when it stops.

New input system

wintry quarry
#

And is this for all buttons or just this one

fleet ivy
#

This one and another, not all of them

wintry quarry
#

I think you need to just have custom handling for this

#

Don't use a regular button