#💻┃code-beginner

1 messages · Page 197 of 1

polar acorn
#

one of them makes a boolean named jump that is false. The other makes a boolean named jump that is true.

shell bane
#

The main camera is on the second screen, the first one, which is the menu, does not have a camera and is working normally, which I find strange

polar acorn
#

Is your main menu an overlay canvas? You wouldn't be able to see anything behind the overlay, but you do still need a camera to render the overlay on

#

Adding a camera to your menu scene means it can now properly draw the overlay, which is over everything

#

You want to either unload the Menu scene when you change scenes, or disable the canvas

teal viper
#

Pretty sure there is something. Did you check the documentation?

shell bane
#

I didn't understand

frigid sequoia
shell bane
#

public void jogar()
{
SceneManager.LoadScene(nomeDoLevelDeJogo);
}

when i press "Jogar"

teal viper
polar acorn
# shell bane I didn't understand

It looks like your menu is being drawn over the second scene. Assuming your screenshot earlier was showing that both scenes are loaded at the same time

teal viper
shell bane
frigid sequoia
#

I did check that, I don't think any of those does what I want

teal viper
#

You are the one who brought up the animation component, so do check it's documentation properly.

frigid sequoia
#

Oh, yeah, that's what I was doing wrong

#

I see it now, thx

#

I was using just animationClip for it for some reason

dull arch
#

Trying to bind jump to the space bar

#

Having a hard time

shell sorrel
#

well Move would does its things for 1 frame, and its not a good tool for this

#

unless thats your own move method, in which it depends in its implmentation

#

also syntax error in your code, you are missing a character and your editor is trying to point it out to you there in red

teal viper
fleet granite
#

are animation parameters exclusive to the gameobject with the animations or can i use the same one on a different gameobject

teal viper
dull arch
teal viper
dull arch
teal viper
#

Each open bracket ( needs a closing one )

#

Makes sense?

dull arch
#

yeah

latent bone
#

Am i allowed to send my code here to get help?

teal viper
#

Yes, if you share it properly.
!code

eternal falconBOT
latent bone
#

can i just send a screenshot?

teal viper
#

Unless there is a specific reason it has to be a screenshot, no.

latent bone
#

okay

shell sorrel
#

a screenshot makes it harder for people to help, since they cant search it or copy and paste

dull arch
#

thanks for the tips also

latent bone
#

Basically, in my scene i just have 6 tiles and im trying to store which tiles are adjacent to each other and they all have appropriate tags (e.g the top left tile is north america etc)

queen adder
#

Okay, but shaders do not have inheritance or anything. Like there’s no base shader i could modify to make this work. Wouldnt i have to also edit the Tmp shaders to achieve this aswell?

dull arch
#

@teal viper you can just notlikethis and not say why your notlikethis

shell sorrel
#

most would copy and paste and modify, or use includes in the shader to grab already defined functions from elsewhere for things

teal viper
dull arch
#

I should I share code

latent bone
#

can someone take a lil look at my code potentially pls 🥹 👉 👈

teal viper
summer stump
dull arch
latent bone
dull arch
#

my bad guys

summer stump
dull arch
#

will do in the future tho

latent bone
#

oh mb sorry

summer stump
queen adder
# teal viper Yes and yes.

Maybe a good first step would be doing it with 2 simple ui images overlapping using the default ui shader

#

But I’ve looked at tmp shaders before and there’s no way I’d ever figure this out for those

#

Without breaking something

#

So it’s hard to be motivated

latent bone
#

@summer stump

#

i dont wanna clog up the chat with screenshots so theres 2

#

and the rest just have tags like "Europe" or "Asia" etc

summer stump
#

If these are prefabs, why use FindWithTag?

It looks like the tags are set right though

latent bone
#

if theres a better way of doing what im trying to do then i could do that?

teal viper
latent bone
#

i still dont get why my code doesnt work tho

summer stump
eternal falconBOT
#

:teacher: Unity Learn ↗

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

cinder basin
#

guys i was following with brackeys tutorial on unity 2d games and i faced an issue with the collider being rapidly enabled and disalbed on its own ,i told someone on the #💻┃unity-talk and he said to share my code here so hopefully someone can help me,
here is the movement script i made:

using UnityEditor;
using UnityEngine;

public class movement : MonoBehaviour
{
    public CharacterController2D ctrl;
    [Range (0f,100f)]
    public float speed = 40f;

    float horizontal = 0f;

    bool jump=false;
    bool crouch = false;
    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal")*speed;
        if(Input.GetButtonDown("Jump")){
            jump = true;
        }
        
        if(Input.GetButtonDown("Crouch")){
            crouch=true;Debug.Log("c");
        }
        else if(Input.GetButtonUp("Crouch")){
            crouch=false;Debug.Log("!c");
        }
        
    }
    void FixedUpdate(){
        ctrl.Move(horizontal*Time.fixedDeltaTime,false,jump);
        jump = false;
    }
}

and here is the 2d controller brakceys provided:

summer stump
#

And I mean, the debug prints from the findalltags("Europe") part

eternal falconBOT
latent bone
#

wdym @summer stump

cinder basin
slender nymph
#

pretty self explanatory

cinder basin
#

sorry im new here

summer stump
# latent bone wdym <@349017582105526273>
Debug.Log(GameObject.FindWithTag("Europe").GetComponent<Territory>().adjacentCountries[0].gameObject.tag);
        Debug.Log(GameObject.FindWithTag("Europe").GetComponent<Territory>().adjacentCountries[1].gameObject.tag);

This is what prints

So, just the two adjacent to Europe

latent bone
#

yes

#

yes thats what i want it to print. but it doesnt print that

#

it prints the two that are adjacent to South america

cinder basin
latent bone
#

And Idk why, but the first thing that i tested it with was south america, so that might be why?

dull arch
teal viper
summer stump
spiral narwhal
#
MissingReferenceException: The object of type 'PlaceableObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Props.DestroyableObject+<>c__DisplayClass4_0.<DestroySelf>b__0 (System.Int32 _) (at Assets/Scripts/Props/DestroyableObject.cs:37)

Why do I get this error on line 37, if the object is destroyed after that?

PlaceableObject Script:

private void DestroySelf()
        {
            foreach (var drop in _drops)
            {
                if (!Chance.Of(drop.Chance)) continue;

                var amount = Random.Range(drop.MinAmount, drop.MaxAmount);
                Enumerable
                    .Range(0, amount)
                    .ToList()
                    .ForEach(_ => ItemDropService.Instance.DropFrom( // <--- LINE 37
                        transform.position,
                        PlayerMovement.Instance.GetFacingDirection(),
                        drop.Item)
                    );
            }

            if (!_destroyOnDeath) return;

            UnregisterSelf();
            Destroy(gameObject);
        }
teal viper
#

Though the fact that it's a PlaceableObject should give some clues.

latent bone
summer stump
teal viper
latent bone
summer stump
latent bone
#

when it should be the adjacents to the europe one

teal viper
latent bone
#

Territory is just a script tho

cinder basin
#

alright so once again but with code share as needed:

guys i was following with brackeys tutorial on unity 2d games and i faced an issue with the collider being rapidly enabled and disalbed on its own ,i told someone on the ⁠unity-talk and he said to share my code here so hopefully someone can help me,
here is the movement script i made:
https://gdl.space/nepawutuka.cs
and here is the contolller brackeys made:
https://gdl.space/zucudutepu.cpp
please help i have no idea whats going on

teal viper
latent bone
#

ok how do i do that

#

sorry im new

teal viper
#

Make the field public

latent bone
#

it is

summer stump
#

They are properties

teal viper
#

Then take a screenshot of the whole component

#

Ah, make the backing field public

summer stump
#

You need [field: SerializeField]
Edit: yeah, that's it

latent bone
summer stump
#

Line above, or same line before the rest of the code

latent bone
#

[field: SerializeField] public List<Transform> adjacentCountries { get; set; } ?

#

like this

cinder basin
#

i feel unimportant sadok
please help me

#

anyone

#

pleeeeeaase

teal viper
#

If you really need help, start from providing more info on the issue. Like a video of the issue.

summer stump
cinder basin
latent bone
#

okay its a step in the right direction, but now my code prints this (i changed the Country in the debug log to Asia)

cinder basin
summer stump
#

Because it doesn't do any of that in the one you shared

cinder basin
#

i showd both didnt i ?

summer stump
cinder basin
#

yea

summer stump
#

Do you mean the bottom one is one you have

#

I assumed it was just what they wrote and you werent using it

cinder basin
#

no the complex one was made by brackeys(the 2d controller)
the other one i made (the movement one wich look simple)

summer stump
#

Ok, looked through that one and still dont see anything setting colliders inactive
Can you give a line number?

Honestly, that code is rough though

warm anvil
#

Good evening - I'm curious, whenever I see tutorials about Scriptable Objects, it always seems to include setting a Menu item for creation of the object. Is this part necessary for Scriptable Objects to work? just seems a little too coincidental that all videos I see, it's included. Thanks!

summer stump
warm anvil
#

cool, thanks @summer stump

summer stump
#

They are asset files, so you will generally want multiple of them, otherwise why even use an SO?

cinder basin
latent bone
#

oh wait @summer stump i just realised that what you said completely fixed it im pretty sure, so thank you for your help. Can you just explain to me what [Serialize field] means and what it does so i know for next time

shell sorrel
cinder basin
shell sorrel
summer stump
summer stump
#

I just think none of that code is relevant to the issue

cinder basin
summer stump
vale karma
#

Im still dealing with this movement state machine issue. how can i reference the rigidbody.velocity from the rb component of the player onto the PlayerIdleState? Any way that I know of trying gives me a null reference error during runtime. https://paste.ofcode.org/8NfSyqskSeXqAxiREAu2bY Edit: I replaced the parts that give errors with Input.GetAxis(Keycode)

teal viper
#

Recording a video would be better if you can't explain it in words properly.

teal viper
cinder basin
# teal viper Start from explaining your issue properly. We're still not sure we even understa...

alright,so im following up with brackeys tutorials and got to the part where i learn about movement , he said it was best to give the player 2 separate colliders and disable the top one to crouch , a circle one for the lower part of the body and a square one for the upper part which is supposed to be disabled when i want to crouch ,however the box collider is rapidly being disabled and enabled on its own without any relalted input which causes the player to get jittery when trying to move against a wall or so /
hopefully htis was a bit clearer

vale karma
#
    {
        Debug.Log("Help! I hope you see me!");
        if (playerMovement.rb.velocity > Vector3.zero)
        {
            player.SwitchState(player.WalkState);
        }
    }

I tried using PlayerMovement playerMovement;
the if statement throws an error, i tried GetComponent<Rigidbody>()

teal viper
cinder basin
#

ill try

teal viper
vale karma
#

on the PlayerMovement script

teal viper
vale karma
#

This happens when i use the method playerMovement.RigidbodyMovement(walkSpeed) too

#

should i assign it to a vector3 variable? since im using position?

teal viper
#

Let's start from basics. Do you understand what a reference type is?

vale karma
#

yea a variable holds the data and a reference type points to the data

#

theres probably better wording but yea

teal viper
#

A variable holds data?

#

So, a variable can't be of a reference type?

#

What does this line in your script do?

    [SerializeField] PlayerMovement playerMovement;
vale karma
#

i figured it allowed this script to see the other script, or use a copy of it

teal viper
#

No.

#

What is that line called?

#

What are you doing on it? Is it a declaration? A definition? Initialization?

vale karma
#

uhh not sure, probably initialize?

teal viper
#

No.

vale karma
#

ooo so close

static cedar
#

Real.

teal viper
#

It's a declaration. What does a declaration mean?

#

Did you go through this stuff? It's all C# basics, that you should go over before even touching the code.

vale karma
#

lol im pretty well adapt to coding, im just not great at it

#

im just getting stumped with one part of it lol

teal viper
verbal dome
vale karma
#

okay, ill figure this out on my own. I figured if i knew what the answer was i can work back and see what i did wrong more clearly. I get your super smart but i dont need a lesson man i can teach myself

static cedar
#

To go back to reference types.
References are also data... that references another data.
Every time you access something through a reference type, you're indirectly accessing the data in the reference.

shell sorrel
#

value type is everytime you pass it somewhere you copy it, refernece type is you just copy and pass its address so the other thing knows where to access it

teal viper
# cinder basin here is the video

Here's the code that enables/disabled the collider:

            // If crouching
            if (crouch)
            {
                if (!m_wasCrouching)
                {
                    m_wasCrouching = true;
                    OnCrouchEvent.Invoke(true);
                }

                // Reduce the speed by the crouchSpeed multiplier
                move *= m_CrouchSpeed;

                // Disable one of the colliders when crouching
                if (m_CrouchDisableCollider != null)
                    m_CrouchDisableCollider.enabled = false;
            } else
            {
                // Enable the collider when not crouching
                if (m_CrouchDisableCollider != null)
                    m_CrouchDisableCollider.enabled = true;

                if (m_wasCrouching)
                {
                    m_wasCrouching = false;
                    OnCrouchEvent.Invoke(false);
                }
            }

If it enables/disables rapidly, it means that the conditions are changing every frame or so. Check what conditions are changing and why. Use logs or the debugger to figure it out.

teal viper
cinder basin
#

ill try tomorrow gotta sleep now

#

cant even htink straight rn

vale karma
#

i spent a day or two going over unity basics, and before this i spent a month or so in it, i mean its not hard to not understand something here or there, If i was able to make it from not knowing how to move a character to the new input system and then now statemachines with a couple minigames under my belt, i mean, i feel like i got farther than go back to square 1

teal viper
#

We're talking about code here. About how C# works. This has nothing to do with unity or character movement.

#

Or input system.

#

Or state machines.

#

What you miss is exactly the square one.

#

And you try to build something on that missing square. Obviously it's gonna collapse.

vale karma
#

okay, sorry. Ill figure it out.

static cedar
teal viper
# vale karma okay, sorry. Ill figure it out.

I think that's also an issue. It seems like you try to figure something out on your own, but eventually get a wrong understanding. Then come back here after it's not working. Instead of repeating that loop, maybe try back up your understanding by asking here wether you get it correctly.

slender nymph
static cedar
#

It's not?

#

Also I thought C# is general purpose language. UnityChanThink

slender nymph
#

structs, which are value types are also objects in c#

#

because everything is an object in c#

static cedar
#

Oh yeah.

shell sorrel
#

which you choose really depends on its purpose and how big it is

static cedar
#

And have one manager class to manage them.

shell sorrel
#

C# does the value vs reference type thign with structs vs classes, other languages just let you choose on the go wether you pass it via a pointer or directly

cosmic dagger
#

i think the biggest misconception i've heard is that value types exist on the stack and reference types exist on the heap . . .

shell sorrel
#

references almost always end up in heaps, for value types its every devs favioute phrase

#

"it depends"

static cedar
#

Well I think "if it's inside the function, a struct is on the stack" will suffice.

shell sorrel
#

before worrying about performance and if its heap and stack you should think about how you are using the data and which is more suited

cosmic dagger
shell sorrel
#

also even in cases where its on the heap anyways like its a member of a array or list, structs can still help things along

static cedar
#

Ok, declared inside a function.

shell sorrel
#

since instead of a array of references to things elsewhere in memory, you get a array to just the thing you want

#

but would always choose first based on how its used and if you want the shared mutablity or not

cosmic dagger
#

value types are only stored on the stack when declared as a local variable or a method parameter . . .

shell sorrel
#

also even as a local var are some cases that make it escape and end up on the heap

static cedar
queen adder
#

why talk about stack and heap here, its a managed language lol

queen adder
#

just making it more complicated for the person who is learning..

cosmic dagger
queen adder
#

Oh nvm

#

someone trying to microoptimize

shell sorrel
#

also the bigger message i am trying to get along anyways is choose mostly based on if you want shared mutability or not, and if you want to compare it based on value or identity

slender nymph
# static cedar How?

boxing a value type is one way to allocate it on the heap. or if the compiler determines the lifetime of the variable exceeds whatever expected time to be on the stack would be. there's actually a few ways to get a value type on the heap.
I wish i could find the really in depth article i read a few years ago about GC and struct allocations cry

static cedar
#

Oh you meant it like that.

#

I was imagining some breaking way to make a stack memory leak somehow.

shell sorrel
#

its really something not to get indepth about unless you are having issues iwth allocations and gc

#

use what is best suited to your logic and has the most clear intent

#

if there are issues a perf wise profile and learn why

cosmic dagger
#

yeah, if you're boxing value types intentionally, then shame on you . . .

static cedar
#

Yeah I always avoid boxing.

shell sorrel
static cedar
timber tide
#

Should I consider implementing an interface specifically for ID, or perhaps I should generalize it a bit more between assets? Maybe have a ISerializeID which extends into IItemID and IProfileID that are just naked interfaces

cosmic dagger
timber tide
#

Or maybe a better question is how grouped should these IDs be between every type of assets? Older games it seems like IDs are very much global due to limitations, but even today I've seen games group monster IDs and item IDs together

static cedar
#

I think IEnumerable methods will get boxed though. Even though it's a struct behind it.
Or does the compiler change it?

static cedar
#

I use generic methods to avoid it getting boxed.

summer stump
queen adder
#

sorry i misread the entire conversation

#

i thought someone was asking for help but it was really just a debate about the specifics of the language

shell sorrel
#

if it wasnt managed people would not care, like in C i know whats on the heap since i had to manually allocate it

summer stump
#

Yeah, that's why I was confused by that. Knowing this is certainly not a microoptimization.

static cedar
#

What happens if you allocate too much in managed and unmanaged languages?

#

I guess in C you would get segmentation faults?

summer stump
static cedar
#

Which slows down the program?

shell sorrel
#

causes hitching

summer stump
shell sorrel
#

cleaning up GC is a total stop the world event, so the frame it happens on will be longer then the rest

#

its a little better with incremental gc used now, but still not a place you want to be in for a smooth gameplay experience

static cedar
#

What's a good place to call GC.Collect?

shell sorrel
#

99.9% of the time never do it your self

#

if you are having problems with GC, you should be looking into why you are allocating so often

#

and by problems i mean having the spikes actually negativlity effect your games performance on target hardware

#

are many ways to avoid it, like the NonAlloc versions of the various physics casts

#

object pooling any object you are instantiating and destroying often

teal viper
shell sorrel
#

simpley just reusing in place any large data structures you need

#

yeah allocating too much and not free is just a memory leak

#

it wont really error from that till its causeing problems for your whole system

gaunt ice
#

os will kill your program if you try to use too much memory
though you can set the limit

shell sorrel
#

yeah things can get pretty high before that happens though, have had a game that was leaking memory using all my ram and was causing the whole system to slow down due to swapping

twilit dirge
#

Hopefully this is the right section. how would i go about a typewriter text?

#

Right now I'm doing it with a couroutine just revealing one character at a time

cosmic dagger
twilit dirge
#

But, this obviously only works if the game is unpaused, and I want to pause the game while talking in dialogue

slender nymph
#

that's the typical way to do it

north kiln
#

Also, make sure by "revealing 1 character at a time" you mean using TextMeshPro's maxVisibleCharacters

#

and you don't mean modifying a string

cosmic dagger
#

you can have all the text already there and increase the maxVisibleCharacters field from TMP . . .

deft siren
#

its not incriesing the drinkTimes when i press E, whats wrong?

frosty hound
#

It's Update, not update

cosmic dagger
deft siren
#

i am incredibly sorry, and ashamed. thank you for your time

deft siren
#

when it suposedly deactivates the objects they flicker for some time before really dissapearing, i rlly dont know whats happening pls help

faint sluice
summer stump
#

Debug drinkTimes to see if it's going up more than expected

faint sluice
#

Or just keep a debug at start of coroutine

summer stump
#

Also, if it's not changing, you can do this
public WaitForSeconds waitTime;

This means you don't have to allocate new ones each time

deft siren
#

i made it so the counter goes up once it calls the courotine and its fixed, thanks a lot!!

vale karma
#

i fixed the issue, I was just creating an empty object and getting the value from it(which was null) i think. Heres the code that works. I dont really understand what 'player' means and i guess thats why i never thought of using it.

{
    NewInputSystemValues movement;

    public override void EnterState(PlayerStateManager player)
    {
        movement = player.GetComponent<NewInputSystemValues>();
        Debug.Log("Hello From the Idle state :D");
    }

    public override void UpdateState(PlayerStateManager player)
    {
        if (movement.MovementAction != Vector2.zero)
        {
            player.SwitchState(player.WalkState);
        }
          
    }```
 It has to do with the state machine and base class for example
```public abstract class PlayerBaseState
{
    public abstract void EnterState(PlayerStateManager player);```
im not sure what it does so i think i gotta watch the tutorial again
teal viper
#

player is a reference to an instance of a PlayerStateManager, which is apparently a component.

static cedar
#

Is this garbaj's tutorial?

vale karma
teal viper
static cedar
#

Yeah also, if you don't know how abstract and virtual and override works it might be a bit confusing.

teal viper
vale karma
teal viper
#

I bet it's called from that PlayerStateManager and it just passes this

vale karma
#

yes

static cedar
teal viper
vale karma
#

Yea its alot of new info, but so far i understand it being written, but writing it using my own code is harder to understand, but better if that makes sense

#

'this' is refering to the game object its attatched to right?

static cedar
#

It's always a good idea to write the code yourself if you want to understand it.

static cedar
teal viper
vale karma
static cedar
#

You only really use "this" if you have name conflicts with a method variable.

vale karma
static cedar
#

Since the code defaults to method variables then class variables.

#
public class MyClass
{
   public int num;

   public void Method(int num)
   {
      _ = this.num;
      _ = num;
   }
}
#

The num without the this keyword will refer to the num inside the method.

vale karma
#

and this.num will use the public int num?

static cedar
#

Yes.

vale karma
#

oooooohhhh i just had an epiphery

#

i had no idea how that related to my code, but after the tunnel vision i see public PlayerBaseState currentState; up top so it is making sense now

calm coral
#

Hey, I have an instance of VideoPlayer and after playing a video I need some kind of animation that it disappears, decays within 1 second like a transition of increasing its transparency from no transparent at all to fully transparent. Is there some way to do that?

#

I would just toggle active state of this game object but that would be immediate, I was wondering if I can make a transition that it fades out within 1 second

teal viper
#

What's the target?

calm coral
teal viper
#

Hmm... What about that alpha? Can't you lerp it to 0?

calm coral
teal viper
#

Probably. Check the docs for more details.

faint osprey
#
    {
        currentWeapon = SV.currentWeapon;
        Instantiate(currentWeapon);
        currentWeapon.transform.position = holderPosFront.transform.position;
        currentWeapon.transform.parent = holderPosFront.transform;
    }```
this is my start function on my players weapon handler however for some reason it only runs the first two statements
#

ive put a dubug at the bottom and that still gets called

#

ive just seen the area Transform resides in a Prefab asset and cannot be set to prevent data corruption

#

how do i fix that

#

dont worry i think i got it

teal viper
# faint osprey how do i fix that

You are trying to modify the prefab(the one that sits in your assets), not the instance that you instantiate. Check the Instantiate method documentation. What does it return?

static cedar
#

currentWeapon = Instantiate(SV.currentWeapon);
Either way, seems like he got it.

calm coral
calm coral
#
void Start()
{
    intro.loopPointReached += IntroComplete;
}

async void IntroComplete(VideoPlayer source)
{
    float completeTime = Time.time;
    float timeDiff = 0;

    while(timeDiff <= 1)
    {
        timeDiff = Time.time - completeTime;
        source.targetCameraAlpha = 1 - timeDiff; // here is the alpha change that makes the transition, perfect!
        await Awaitable.EndOfFrameAsync(destroyCancellationToken);
    }
}
```Yes, this works all perfectly and I got what I wanted, thanks again a lot @teal viper it's not the first time you were so helpful!
north kiln
#

I kinda imagine you want NextFrameAsync, not EndOfFrameAsync

calm coral
#

It seems both are working

north kiln
#

it's the difference between waiting until a normal time in the frame, or after everything has completed and when the frame is rendering

#

NextFrame is similar to yield return null, which is the usual behaviour

calm coral
#

Aight catStare thanks!

timber tide
#

Cleaning up some of my prefabs and now I'm debating on how I want to reference all my components. Should I consider just having a root component that serializes all references for each individual component used by the prefab, and then give each of these components a reference to the root (bidirectional referencing). Or, should I just require each component to serialize the references to the components they specifically need?

#

I'd have to make multiple different classes probably with this root component idea since each implementation would be different depending on the prefab.

night mural
#

imo the scene should not be the source of truth for any gamestate, just a visual representation of it (so you would never need to directly serialize a prefab or its components)

timber tide
#

this is all on the prefab itself, such as a player prefab / enemy prefab

night mural
#

even if you do go that route, i think it makes sense to decouple serialization from those components themselves and have something in charge of collecting up/saving whatever things you actually need to persist

timber tide
#

for what I've been developing, I've noticed a lot of my components need references to my animator or my stat component, so I thought instead of binding that reference 10 times throughout the prefab, why don't I just give it a reference to a collection of references?

night mural
#

sounds like that's what you'd serialize then?

timber tide
#

yeah, I know, but gotta go throughout the whole prefab to match references which can be a lot of mix and matching

#

I guess it's more of an issue that I do have problems with serialization breaking and me having to go back and rebinding it all

night mural
#

yeah, i don't know of a good solution for that other than my suggestion of 'make it so you don't have to do it'

timber tide
#

I had a lot of stuff binding via getcomponent with onvalidate, but the hierarchy isn't always similar to other prefabs so I need to rid of that idea.

vale karma
#

is there more documentation on creating state machines for movement? im watching iheartgamedevs tutorials on statemachines and each video it changes the type of state machine he has/rewrites it. Its hard to follow this way bc the earlier videos are flawed so i dont want to follow it, but his recent video is completely different than what i made already

#

so i dont want to refactor all my code to the first videos machine, then the second, then third, id rather learn the most optimized way from the getgo

vale karma
#

i dont think i have, ill try it

static cedar
#

You don't have to start from part 1 on his tutorial, he completely rewrites it starting around 20.

#

It's also around there he specifically makes finite state machine for managing player movement.

vale karma
#

okay, i feel like i dont know enough about them to pick what i need to do now, right now i have 2 movement scripts and a bunch of state machines and im getting stumped more and more as i go

#

a refactored moving script lol im still completing the new movement script

#

i have questions like "how do i integrate my scripts into a state machine?" they never show that, just mainly how to build it. or even "How can i make a hierarchical state machine while using the state machine i just made"

static cedar
#

Are you asking how state machines work?

#

I could probably describe it. :P

vale karma
#

no i understand how they work, just not how to implement it into my code and make it work

#

i get stuck on things like, "should this stay in the movement script or should it be moved to the statemachine?"

static cedar
#

Is that really understanding if you don't know both? O.o

vale karma
#

no, i understand the concept of them but not how to use them ;D

#

even then if i try and lookup some written documentation its always about the animator and not the code

#

the entire time ive tried learning how to make a game i keep getting stumped on WHAT i need to learn. Noone ever tells you the next thing you should do lol

static cedar
#

Well for starters, all state machine rely on polymorphism. Basically, it's being able to use something, without knowing what it specifically is.

#

All the states you've made like WalkingState and IdleState have methods like EnterState and ExitState.

vale karma
#

yea im stuck at a point trying to find out how to run Exitstate after a command in EnterState.

#

basically im jumping twice if im fast enough

static cedar
night mural
vale karma
#

and im running into problems where i have to write IsGrounded on every state that needs it or switch the state to Jump on every movement state... its a mess DX

static cedar
#

It's a bunch of if statements.

vale karma
#

yea thats what im trying to avoid, i know that you can make a hierarchical state machine with jump and grounded able to happen at the same time as the other states without having to hardcode each state to it

#

I just dont have the bigbrains yet

static cedar
#

The tutorial could make a OnGroundState that IdleState and WalkingState inherits from so you don't have to rewrite it over and over. But you might get more confused considering that you're not really used on thinking about these inheritance patterns yet.

sour ruin
#

debug.logging rb velocity gives 0, 0, 0 even though the player is moving around correctly (this is being called from fixed update)

charred spoke
#

A hierarchical state machine means that you can have another state machine as a state. Basically nested state machines it does not mean you can be in two states at once. No state should or does that.

timber tide
#

stuff like IsGrounded is more of a global flag than a state

vale karma
#

oh, god my brain

timber tide
#

or rather Uri's suggestion of hierarchical states

vale karma
#

ill have to restart and build from what i know until i start getting destructive again, and recreate this in a more organized and structured fashion

static cedar
#

Not sure about having multiple state machines.

vale karma
#

yeaa, the way uri puts it its not as fun to have

static cedar
#

Can't the state themselves be in a hierarchy pattern?

vale karma
#

yea like reading left to right, but if i want IsGrounded and Jump to be able to happen from any of them, thats alot of spegetti the whole thing was implemented to avoid

static cedar
#

BaseState: Defines basic functions for each state.

  • OnAirState
  • OnGroundState: Defines the functionality to jump or transitioning to OnAirState when not in ground.
  • WalkingState: Walking left or right.
  • IdleState: Standing idle.
vale karma
#

this hurts my brain, i must absorb

static cedar
#

Real.

charred spoke
#

You dont need a onGroundState for a statemachine like that

vale karma
#

it doesnt help the same guy put out 4 tutorials on the same topic within a 6 month period of revisions

charred spoke
#

Well dont follow that tutorial then

static cedar
night mural
vale karma
#

eya im watchin this 2d one now lilac mentioned

#

@night mural i refactored my code to look really nice, but then got to a spegetti-if halt from the multiple features i wanted the movement to have. I want basic crouch, run, jump, walk, and idle movements, which is simple, but i know i will need more than that for future games

night mural
#

sometimes complex things require complex code

#

just be careful getting stuck re-implementing the same thing a bunch of different ways before you're sure if you actually need it and why

vale karma
#

okay ill remember

timber tide
#

just stick stuff in methods even if it's not reusable and it'll look less spaghetti

static cedar
#

Guard clause exists.

night mural
static cedar
#
if (!grounded)
{
   state_machine.ChangeState(onair_state);
   return;
}

if (input.x != 0)
{
   state_machine.ChangeState(walking_state);
   return;
}
#

This much is unavoidable.

vale karma
#

^^thats how i have it rn, but the jump state jumps twice if im quick enouch

#

im okay with that

static cedar
vale karma
#

i wanted to implement a counter for it, but failed lol. so unless i want to jump high randomly im stuck here

#

that leads to why i figured changing the state from both idle and walking to jumping seems redundant and could cause that

#

it goes to walking, i heard something about substates for when it could go to either of them, but idk how it works

static cedar
vale karma
#

i dont have onairstate, but rather Jump state. but yes, when the spacebar is pressed, the Walking/Idle state checks if its grounded then changes state to the Jump state. The EnterState() function runs playerMovement.Jump()

static cedar
#

Does your jump state have a ground check?

vale karma
#

and the update function checks if its grounded to change it to walkstate.

#

it did, i took it off since i figured its asking twice bc its switching states

#

i had it on the method, state, and previous state at the same time too

static cedar
#

You can fix this by having a minimum time to be in jump state.

vale karma
#

yea im seeing it now, its called 6 times every 1 button press

static cedar
#

Sounds cracked.

vale karma
#

im guessing a corutine would work?

static cedar
#

The states should suffice with only on frame updates.

vale karma
#

couldnt i put a set amount of time before it switches? idk how to add a certain amount of time to it

static cedar
#

And another float parameter on how long you have to stay on jumping state.

#

Add those two floats on update and check if it's less than current time.

teal viper
#

Another way is to make the grounded/jumping condition more robust. For example, checking the character velocity. If it's upwards, it doesn't make sense to transition to grounded state.

vale karma
#

what if hes walkin up a hill? wouldnt that go up in velocity?

static cedar
teal viper
#

Well, it depends on the project of course, but the point is, to identify correct conditions for transition. If you're going back and forth between states every frame, it's not a solid state machine.

vale karma
#

is there any other way to have a good state machine with jumping? i cant think of anything else that could check more accurately than isgrounded

static cedar
#

You totally need a isgrounded.

teal viper
#

So slopes shouldn't be a problem.

static cedar
#

Jumping and landing.

teal viper
teal viper
#

You can't land on something while moving upwards.
Unless you have custom physics and orientation mechanics.

#

Like changing the gravity to point up and stuff.

static cedar
teal viper
#

Okay, I see that one case. But that can be handled separately.

vale karma
#

i figured i could do something like jump in the enter state if a bool is true, then set it false, then go to the ExitState() and set a bool to true and switch

#

it seems easier if i just want to jump once

static cedar
#

Your jump force isn't on enter state?

vale karma
#

nah, its in the movement script

static cedar
#

That's fine too.

teal viper
#

For example instead of simple velocity direction check,check it against the surface normal, and if the directions meet, consider it grounded.

static cedar
#

But you still have to prevent false positives when the jump state changes to the ground state.

eternal needle
#

i find its sufficient to just check the grounds normal along with if you jumped recently, you are likely gonna have a jump cooldown anyways. So you can use this cooldown to see if it makes sense for the player to be grounded

static cedar
#

Yes but you don't change how your ground check works.
Do as dlich and I suggest to only add the extra conditions specifically on the jump state.

vale karma
#

so i took out the ground checks for the other states, is it good enough to just have the groundcheck on the updatestate for Jumping?

#

nah its still happening

static cedar
#

Why did you took out the ground check for other states?

vale karma
#

oh wait what are the extra conditions

static cedar
#

Only the jump state prematurely moving to ground state is the problem.

vale karma
#

how do i get it out of the jumpstate then?

static cedar
vale karma
#

uhh 1.0 is equal to 1 minute right?

tepid summit
#

hey would anyone like to give a brief explanation of instantiate? (ive only ever used it for guns & shooting so my brain just automatically goes: hehe funny gun word).

static cedar
#

Time is measured in seconds in unity.

#

You only need like a fraction of a second for a minimum time.

vale karma
#

1 is too much, .001 doesnt work, .01 doesnt exit still

teal viper
tepid summit
#

that was my basic idea

#

like a cloning feature

vale karma
#

i cant jump anymore after the first jump

#

probably bc i didnt reset it haha

static cedar
#

Post code.

#

Of your jump state.

vale karma
#

nvmd didnt work

tepid summit
#

that makes sense

#

i was instantiating the bullet and adding force

#

im learnding

vale karma
#
using Unity.VisualScripting;
using UnityEngine;

public class PlayerJumpState : PlayerBaseState
{
    PlayerMovement playerMovement;
    float currentTime;
    float waitTime = .1f;

    public override void EnterState(PlayerStateManager player)
    {    
        currentTime = Time.deltaTime;
        Debug.Log(currentTime);
        Debug.Log("JumpState Enter");
        playerMovement = player.GetComponent<PlayerMovement>();
            playerMovement.Jump();         
    }

    public override void UpdateState(PlayerStateManager player)
    {
        if (playerMovement.IsGrounded() && currentTime > waitTime )
        {
            player.SwitchState(player.WalkState);
        }
    }
}```
tepid summit
#

why do you have a specidic float for deltatime

vale karma
#

no idea

tepid summit
#

ok

#

dont you have to make states before using them

static cedar
vale karma
#

no idea

static cedar
#

Time.time for current time.

tepid summit
#

what is currenttime meant for

tepid summit
static cedar
vale karma
#

loll yea i never used Time.time, so i looked at whatever options come after the .

static cedar
#

Also your if check is also wrong.

#

Time.time > currentTime + waitTime

#

Rename current time to

#

The time the state became jump state.

#

Crunch that sentence lol.

#

stateStartTime might work.

static cedar
vale karma
#

okay i got it all written, lets see if it works

#
    PlayerMovement playerMovement;
    float waitTime = .2f;
    float stateStartTime;
    public override void EnterState(PlayerStateManager player)
    {
        stateStartTime = Time.time;
        Debug.Log(stateStartTime);
        Debug.Log("JumpState Enter");
        playerMovement = player.GetComponent<PlayerMovement>();
            playerMovement.Jump();      
    }
    public override void UpdateState(PlayerStateManager player)
    {
        if (playerMovement.IsGrounded() && Time.time > waitTime + stateStartTime )
        {
            player.SwitchState(player.WalkState);``` this works
static cedar
#

What script is this?

vale karma
#

jumpstate

static cedar
#

Ah ok.

sour ruin
tepid summit
#

are you applying force or changing transform

sour ruin
tepid summit
#

debug.log to see if targespeed changes

sour ruin
#

it changes

#

currentvelocity works as intended

eternal needle
# sour ruin

force isnt added instantly, it is added after the physics simulation step. your debug.log wont be accurate

eternal needle
#

no, as that depends on framerate and will still have the same issue. Is your debug always giving 0?

sour ruin
#

always

#

gravity updates the velocity correctly i should add

eternal needle
#

can u show the inspector for the rigidbody? also maybe other code is affecting the rigidbody in some way

sour ruin
#

i only have one other section adding forces and that one works correctly

vale karma
#

i got it running, jumping, and sprinting correctly 😄 ill do crouching tomorow

eternal needle
# sour ruin

maybe look at the physics debugger to see its velocity instead. i dont see why this would always log 0, unless the log is only happening when the velocity is 0 beforehand.

vale karma
#

thnks guys catch u tomorow

eternal needle
#

theres likely other code thats affecting this, or the code isnt affecting the object you think it is

sour ruin
#

physics debugger agrees with debug.log

eternal needle
#

that it is 0? then you are likely not affecting the object that you think

#

if you said the object is moving properly, or you have other code moving it

sour ruin
#

this is the only other place the rigid body is being referenced and the velocity is correctly updated

#

here where it is suspiciously not updating velocity correctly, if i comment out the addforce line my character cannot move so it is doing something

earnest atlas
#

why u have AddForce of velocity change and inpulse?

#

So far jumps worked fine with impulse

sour ruin
#

the impulse is being used for the jumping and velocity change for walking

earnest atlas
#

Rb used to move works weird

#

when I tried it likes to get stuck

sour ruin
#

its definitely working since my guy is walking around just fine

#

values just arent being updated though

sour ruin
earnest atlas
flat slate
#

!code

eternal falconBOT
flat slate
#

am i able to implement MoveTowards ther?

#

i want the object that gets the knockback to move to that position so it looks cleaner

earnest atlas
#

you have Vector3 with just 2 variables

flat slate
#

yea

eternal needle
gaunt ice
#

move toward:

T start,T end, float amount
T something_normalized=(start-end).normalized
if(start+something_normalized*amount>end){
  return end;
}else{
  return start+something_normalized*amount;
}
```you need clamp and normalization
earnest atlas
#

I would belive more that he has issues with code then bug with rb that is used a lot

flat slate
earnest atlas
#

yeah moveTowards will move it to position

flat slate
#

but how do i implement that?

gaunt ice
#

dont reinvent the wheel btw

earnest atlas
#

I love reinventing a wheel

#

I spent 2 days coding FPS controller only to decide im done and understand how Unity Asset one works

flat slate
#

im to dumb to do it

#

no wait

bright zodiac
# flat slate but how do i implement that?

I'm not sure if it's actually what you wanted, but here's Unity's impl

        // Moves a point /current/ towards /target/.
        [MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
        public static Vector2 MoveTowards(Vector2 current, Vector2 target, float maxDistanceDelta)
        {
            // avoid vector ops because current scripting backends are terrible at inlining
            float toVector_x = target.x - current.x;
            float toVector_y = target.y - current.y;

            float sqDist = toVector_x * toVector_x + toVector_y * toVector_y;

            if (sqDist == 0 || (maxDistanceDelta >= 0 && sqDist <= maxDistanceDelta * maxDistanceDelta))
                return target;

            float dist = (float)Math.Sqrt(sqDist);

            return new Vector2(current.x + toVector_x / dist * maxDistanceDelta,
                current.y + toVector_y / dist * maxDistanceDelta);
        }
#

there's not much you can do to make it better than it already is other than replacing those divisions, but that will introduce other issues and new edge cases.

graceful citrus
noble summit
#

is it possible to connect a server with other people who have the build for free

timid saffron
#

good morning. what goes in underlined pharantesis? is it just int value or something custom

#

if i wrote int 0 would it start from zero

rare basin
#

if you call the function with AddLives(0)

#

then the value will be 0

#

so 1st line from the function

#

will be

#

lives += 0

timid saffron
#

i gotta make it lives=lives+1 yes?

#

oh

#

wait

#

right

#

lives is 10 this way

#

for initializing it i may use a timer too later

earnest atlas
#

someone writes code on paper omg

#

also if you want to change same variable you can do this
+=,-=,/=,*=

#

its basically a = a+-/* number

timid saffron
#

i read it easier this way

#

thats why

noble summit
#

writing code on paper is elite

eternal needle
timid saffron
#

before IDEs we had paper boy👴

torn gyro
#

hey could anyone help me : (

north scroll
#

does the underscore prefix of a var and private do the same thing ?

torn gyro
#

i tried making an update score function in a box collision script but it doesnt update the text on screen

torn gyro
#

lmao good point

eternal needle
burnt vapor
earnest atlas
#

yeah thats just naming

burnt vapor
torn gyro
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class LogicManager : MonoBehaviour
{
    public int playerScore;
    public Text scoretext;


    [ContextMenu("Increase Score")]
    public void addScore(int scoreToAdd)
    {
        playerScore += scoreToAdd;
        scoretext.text = playerScore.ToString();
    }
}
using System.Collections.Generic;
using UnityEngine;

public class PipeMiddleScript : MonoBehaviour
{
    // Start is called before the first frame update
    public LogicManager LogicManager;

    void Start()
    {
        LogicManager = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicManager>();
    }

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

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {

        if (collision.gameObject.layer == 3)
        {
            LogicManager.addScore(1);
            Debug.Log("added score");

        }
    }
}
#

the first one is for the text to show

#

the second one is the box clission

burnt vapor
burnt vapor
#

See if it's called at all, and see if addScore actually logs the value you expect to write to the screen

burnt vapor
torn gyro
#

seems that OnTrigger isnt beinbg triggered : (

burnt vapor
#

Ok so why are yo not telling this? 🤔

earnest atlas
#

do you have collider set to trigger?

burnt vapor
#

It's very important you share as much info as possible

north scroll
#

ok so an underscore has 0 effect? Cuz ive been trying to look up on google and I keep getting that if you don't have an underscore you might have to do something with classes and pointers (this-> )

hidden sleet
#

Say I have a script on an object that inherits from another class that extends MonoBehaviour,

ParentClass : MonoBehaviour
SubClass : ParentClass```
and I have that subclass attached to an object. If I ask for the parent class in code ```cs
FindObjectOfType<ParentClass>();``` will it pick up an object if the subclass script is attached to an object?
north scroll
#

private would be to make it inaccessible where as the underscore is purely for readability sakes basically, right ?

burnt vapor
torn gyro
#

mhmmm

burnt vapor
#

And consider also logging your trigger behaviour considering that's the part that fails according to you. Place Debug messages and see if they're actually not called. Currently your code only checks if the trigger activates on a certain layer.

torn gyro
#

my game object is set to layer 3

earnest atlas
#

you have BOX collider

#

is it 3d or 2d game?

burnt vapor
torn gyro
#

2 d

earnest atlas
#

you need box collider 2d

#

otherwise on trigger wont get a call

burnt vapor
#

The worst part about helping somebody with debugging their application is when somebody else ends up spoonfeeding the answer

#

Thanks @earnest atlas

torn gyro
#

oh theres one more issue that is easily traceable too

earnest atlas
#

OnTriggerEnter2D (collider2D other) is for 2D
OnTriggerEnter(collider other) is for 3d

torn gyro
#

the context menue doesnt show under Logic manager

#

does that have anything to do with it

earnest atlas
#

I have no idea what is ContextMenu

torn gyro
torn gyro
#

i fucking didnt read that shit

burnt vapor
#

When debugging something like this you might be better off following the most basic example first

#

So see if copy pasing the method from the wiki does anything

earnest atlas
# torn gyro

Not increase score, you need to write there addScore

#
public class ContextTesting : MonoBehaviour
{
    /// Add a context menu named "Do Something" in the inspector
    /// of the attached script.
    [ContextMenu("Do Something")]
    void DoSomething()
    {
        Debug.Log("Perform operation");
    }
}```
burnt vapor
#

That's not at all how to fix the issue, please stop helping if you have no idea how it works 🤦‍♂️

#

You have already spoonfed the previous answer instead of providing a good way to debug the issue, maybe wrap it up for now

#

@torn gyro See if the method from the wiki works for you.

north kiln
#

You can't add it to a method that takes arguments

torn gyro
#

OMG why you guys bully @earnest atlas

earnest atlas
#

are they?

torn gyro
#

his solution was correct

earnest atlas
#

Im kinda not looking

torn gyro
#

idk :/

torn gyro
rare basin
#

but he wasn't bullied for that lol

earnest atlas
#

yeah I had experience with exactly same issue u had

rare basin
earnest atlas
#

im not even sure who he adressed that

torn gyro
#

to u i think : P

burnt vapor
#

The problem is that I'm trying to get you to debug your issue so you can fix any future issues yourself, and they proceed to spoonfeed the answer instead.

#

Now you have no idea how to fix any future problems

rare basin
#

he's always spoonfeeding there

#

with weird fixes

earnest atlas
#

who?

north kiln
burnt vapor
#

I understand people love to help, but please don't spoonfeed an answer

burnt vapor
rare basin
torn gyro
#

im second year cs thinksmart

burnt vapor
#

I see. I don't check this channel as often as I used to

rare basin
#

spoonfeeding should be against the rules lmao

timid saffron
#

my code for this is

if (transform.position.z>35 || transform.position.x >35)
{
Destroy(gameObject);
}
else if transform.position.z<-35 || transform.position.x <-35)
{
gameManager.Addlives(-1);
Destroy(gameObject)
}

how can I make it so that players lives decrease each time a gameobject gets destroyed in either x or z axis? for example my code includes || thats if position is ... or position is... I dont wanna use the code in the screenshot as I want it to be as short as possible

eternal needle
torn gyro
#

gimme internship pls :/

timid saffron
#

there is "||" in code but discord marked it as spoiler

north kiln
timid saffron
#

in if pharantesis

eternal falconBOT
earnest atlas
#

that ^

timber tide
#

a lot of spoonfed questions would be reduced by only answering if they actually debugged their code / printed to console

burnt vapor
#

Yes, that's kind of what I was hinting at

rare basin
torn gyro
#

@earnest atlas @rare basin @burnt vapor thanks yall < 3 this issue took me 2 hours btw i had to look at every single aspect of the project until i gave up and came here

earnest atlas
burnt vapor
#

The majority of questions in here could be fixed by learning to debug

timid saffron
timber tide
#

posting a whole block of code without a single print statement and asking why dis dont work is where my help stops ;)

static cedar
burnt vapor
torn gyro
#

ok

#

you know i had to restart like 5 times cuz i keep pressing play button without saving :/

burnt vapor
#

What do you mean restart? Code should not disappear if you forget to save

torn gyro
#

sprite making

#

and managing inside unity

#

aside from scripts

teal viper
static cedar
#

Coffee script?

burnt vapor
#

Just what the site assumes to be the language used, it's often wrong

static cedar
#

Probably cause of the first line.

burnt vapor
#

Or the fact they wrote the entire question alongside the code 🤔

static cedar
#

Side note, if we suddenly talk about the odd things they did while asking for help, I'd get a bit nervous.

shrewd swift
#

can I update directly a specific axis of the size of Sprite Renderer ?

or is it like Transform and you have to give a whole Vector

static cedar
#

It's because it's a getter/setter. Not an actual field so you can't change something inside directly.

timid saffron
# teal viper What's the problem with this code?

theres no problem. unity wrote this code this way but i wrote it differently and i dont wanna change it because i wanna make it as short as possible. in unitys version players lives decrease when animal is destroyed in x and it decreases when its destroyed in z too. in my version it decreases by one if it gets destroyed in either z or x

#

i wanna make it so that if it gets destroyed in x or z players live decreases by 1 instead of if it gets destroyed in either z or x

teal viper
#

So what's the question?

#

If there is no problem, what's the meaning behind your message?

timid saffron
#

it is how can i make players live decrease if animal gets desroyed in both z and x (-2 lives) instead of it getting destroyed either in z or x axis (-1 live)

#

i used "||"

#

unity didnt

rare basin
#

destroyed in both z and x?

#

what do you mean

teal viper
burnt vapor
timid saffron
teal viper
burnt vapor
#

I assume you want to use && rather than ||

rare basin
#

desroyed in both z and x

#

then yea use &&

#

if you want both conditions

#

why did you use || then

timid saffron
timid saffron
timid saffron
teal viper
#

I still don't get what "unity version" is?

teal viper
timid saffron
#

this is unitys version of code

#

they have 2 else ifs

#

i have one

rare basin
#

ok, so what?

teal viper
#

Wtf is "unity version"??

rare basin
#

from !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

teal viper
#

Unity is a game engine it doesn't write code!!

rare basin
#

they are following a tutorial

timid saffron
rare basin
#

from unity learn

teal viper
#

Ok, so it's "code from a tutorial". Not unity version.

timid saffron
#

i have one

rare basin
#

ok so what about it

timid saffron
rare basin
#

that's unreadable

timid saffron
#

i think using && will fix it

rare basin
#

then check it

#

what is the problem

#

i still dont understand

torn gyro
#

my text look ugly :/

burnt vapor
#

He wanted to check both cases instead of either one, I guess. Hence why && should be used rather than ||

torn gyro
#

i googled it it says resalution

#

but i have it set to 1080p

burnt vapor
#

What are you talking about? 🤔

torn gyro
timid saffron
burnt vapor
#

Or just google "Unity low resolution"

rare basin
#

also this is code related channel

torn gyro
#

thanks

delicate tangle
#

anyone know what "unity NullReferenceExeption: Object reference not set to an instance object" means

graceful citrus
graceful citrus
#

the computer doesn't know what the objects its trying to move are. you have to tell it

delicate tangle
#

oh ok thank you

river glade
#

Hi everyone, how can I solve this problem?

autumn tusk
#

ok i dont understand this in the slightest

#

basically im trying to implement a burst system for my game

#

so being able to fire in bursts

burnt vapor
autumn tusk
#

firing multiple times with one shot i got sorted out, but i cannot get delays between shots working

#

!code

eternal falconBOT
burnt vapor
autumn tusk
rare basin
#

show the code then

burnt vapor
#

Yes it does. What have you tried?

river glade
autumn tusk
rare basin
#

that looks like a custom asset

burnt vapor
rare basin
#

for enviroment

burnt vapor
#

Or ask in a channel with people with experience

autumn tusk
#

getting my issues in the playershoot function

#

line 73 onwards

river glade
faint osprey
#
        {
            if(deathOnce == false)
            {
                deathOnce = true;
                isDissolving = true;
                EH.StartCoroutine(EH.Dissolve(gameObject));
                EH.enemyCount -= 1;
                int randomNum = Random.Range(0, 4);
                for (int i = 0; i < randomNum; i++)
                {
                    GameObject spawnedCoin;
                    spawnedCoin = Instantiate(Coin, gameObject.transform.position + Coin.transform.position, quaternion.identity);
                    spawnedCoin.GetComponent<Rigidbody2D>().AddRelativeForce(Random.onUnitSphere * 1500);
                }
            }
        }```
my coroutine isnt activating
rare basin
#

grass shader

#

it might not be made for HDRP

burnt vapor
#

That's not how a Coroutine works

#

A Coroutine does not magically halt code in a non-coroutine just because you start one

river glade
burnt vapor
#

The code will continue as normal

#

Instead, this code must also be a coroutine

autumn tusk
#

alright

#

makes sense

burnt vapor
#

And you can call a coroutine and yield that one to add a delay, or just add a delay there directly

river glade
rare basin
#

use a grass shader that is made for HDRP

#

or make your own

burnt vapor
# autumn tusk makes sense

Code in Unity is synchronous. Coroutines fake asynchronous code running in the background by having Unity invoke these yield commands. Kind of a complex topic.

#

You can also make actual asynchronous code with Tasks. If you make that function a Task it can also use delays

#

But in Unity async code works the exact same as Coroutines

#

But still very good knowledge to have

#

Have fun reading

autumn tusk
#

im using unity 2022.3.13 sadly

burnt vapor
#

Regular async still applies, or continue using Coroutines

#

Async is just better because the flow is a lot more clear and undisturbed

#

And external libraries will use it, if you ever need them

#

Or upgrade 😎

dusky finch
#

how can i get a hollow circle? is that possible without using some renderer? i would also like to have it as a prefab with other shapes inside it

burnt vapor
#

Probuilder for example, is a tool that allows you to easily make geometry. Idk if it can make a hollow circle as easy

dusky finch
#

thanks ill check it out

quaint flicker
#

I'm using URP and new input system, and I just noticed randomly that if I press both sticks on a controller in play mode a debug stats window pops up. Kinda cool, but also.. where's that coming from? I'm pretty sure I don't have anything to trigger it in my input actions, and my canvas event system is setup to process the new input system. It's called DebugUIHandlerContainer so the debug means this will NOT be in my release build, right?

hexed terrace
#

also.. just do a build and test it ?

visual hedge
#

hello everyone.

[System.Serializable]
public class CapturedPets
{
    public GameObject thePrefab;
    public BaseClass Stats;
    public Level Level;
    public EnemyType Type;
    public EnemyRarity Rarity;
}

how can I actually save the reference to a gameObject? Let's say I plan to use json.
What this class will later do is at the turn-based battle start it will instantiate thePrefab gameobject and then load all the data below.
Is making a string with the path to the gameObject instead of direct reference a way to go?

timber tide
#

you don't save that specific reference per say, instead you construct a new object of that type and populate it with the data you written to your json

#

you can cut down on the data you need to write and read if that specific data is non-unique, such as defaults, which then you can just serialize an ID to be used with a lookup table that you construct from all your prefabs/SOs on startup

visual hedge
#

basically Instantiate(Resource.Load(“object path”))

#

so the code would be changed to something like that:

[System.Serializable]
public class CapturedPets
{
    public string PrefabName;
    public BaseClass Stats;
    public Level Level;
    public EnemyType Type;
    public EnemyRarity Rarity;
}

I think it's solved. Thank you.

timber tide
#

Names are fine too if you wanna do it that way, but always a chance that you've create a prefab of a similar name which is why I suggest adding some IDs in one of your components and do lookup by that.

#

Ah, if it's all in the same directory it probably would resolve itself

visual hedge
#

nah, not an int per se, still string, but anyways...

trail creek
#

guys, i need some help, i can't move in my scene, if i press w it does not go forward

visual hedge
trail creek
#

i can only move the view with the mouse

visual hedge
#

oh... use arrows? )

trail creek
#

they don't work too

#

it's like blocked

tepid summit
visual hedge
#

are there any gameobjects in the scene so you actually are liek dead sure it's not working? ) because I guess it might be tricky in an empty scene

trail creek
#

ye, there are some game objects, i just moved far and it's blocked now

tepid summit
tepid summit
#

no

#

the furhter you are from your game it moves slower i think

#

happens to me from time to time

visual hedge
trail creek
#

oh, but i already tried to re-open my position is still the same

trail creek
#

ok

#

ty

#

sorry

visual hedge
#

works? )

tepid summit
#

works?

#

lol

visual hedge
#

😄

tepid summit
#

omg

trail creek
flat slate
#

!code

eternal falconBOT
trail creek
visual hedge
#

great )

flat slate
#

why doesnt that work

tepid summit
flat slate
#

after the insantiate it doesnt move

tepid summit
#

oh

#

short, sweet and simple

flat slate
#

more details?

tepid summit
flat slate
#

yea

visual hedge
flat slate
#

is that the speed?

visual hedge
#
Coin.transform.position = Vector3.MoveTowards(transform.position, Player.transform.position,0);
``` pretty sure this 0 is speed
flat slate
#

the last number

#

oh damn

#

hahaha

#

didnt know the last int is the speed

#

thanks

visual hedge
#

it should be float actually 😄

flat slate
#

my bad

visual hedge
#

or idk... look at this:

transform.position = Vector3.MoveTowards(transform.position, target, 15f * Time.deltaTime)

that's a part of the string I use to move some of my units around...

#

and animSpeed is a float

flat slate
#

yea

visual hedge
#

also I guess * Time.deltaTime is quite essential there

flat slate
#

still nothing is happening

visual hedge
#

if it's not working, sorry, can't help any further, no idea then

flat slate
#

okay

#

no problem thank u

teal viper
#

0.5 sec after

#

And incorrectly at that as well. TylerWin pointed that.

split dragon
#

Hi. I have a question about optimizing the script: I have texts that show the float value. They work in void Update every time, but if I add: "(if objectsLights[i].activeSelf)", will there be any difference in performance? If the 25th line is removed from the screenshot, will the performance be the same or will it differ? if I added that the text does not always change and does not load the system (according to my logic)

visual hedge
#
private Vector3 startposition;
private float animSpeed = 15f;
                while (MoveToPosition(startposition))
                {
                    yield return null;
                }
    private bool MoveToPosition(Vector3 target)
    {
        return target != (transform.position = Vector3.MoveTowards(transform.position, target, animSpeed * Time.deltaTime));
    }

Idk, that's what I use. Also in terms of IENumerator

rare basin
#

unless you have 10000000 objectsLights

flat slate
split dragon
flat slate
#

i want it to move to the player after its instantiated

teal viper
vale karma
#

my jump action is able to jump when im near the ground, i think the raycast is returning true too late

teal viper
flat slate
#

oh okay

faint trellis
#

you need to put the MoveTowards in Update

keen dew
vale karma
#
{
    int hits = Physics.OverlapSphereNonAlloc(transform.position, capCollider.radius, groundedResults, groundedLayers);
    return hits > 0;
}``` can this be written better? or am i missing something with this IsGround check?
teal viper
#

*in addition to the grounded check

vale karma
#

thats a good idea

flat slate
#

how do i make the object to move till the player is reached?

teal viper
vale karma
#

is there a way to make isgrounded shoot down less than it is?

flat slate
visual hedge
#

at which point is void Start() exectuted after instantiating the object with the script that contains Start on it?

teal viper
flat slate
#

for example a for loop?

vale karma
flat slate
#

ye i know

split dragon
teal viper
eternal falconBOT
#

:teacher: Unity Learn ↗

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

rare basin
#

on

#

not constantly in Update()

visual hedge
# flat slate how do i make the object to move till the player is reached?

please try to implement this code: private Vector3 startposition;
private float animSpeed = 15f;
while (MoveToPosition(startposition))
{
yield return null;
}
private bool MoveToPosition(Vector3 target)
{
return target != (transform.position = Vector3.MoveTowards(transform.position, target, animSpeed * Time.deltaTime));
}

rare basin
#

via events preferrably

rare basin
#

due to floating point precision

outer cobalt
split dragon
visual hedge
rare basin
#

doesnt mean its correct

keen dew
vale karma
# flat slate thanks

you could look into navmesh as well, its a part of enemy navigation it may help u

visual hedge
#

I mean what else would suggest it's incorrect?

rare basin
#

as i said, floating points

teal viper
# rare basin that won't work

Vector3 comparison makes an approximate comparison. Though, I agree that it might not work under certain conditions(not due to floating point error)

visual hedge
#

the coroutine stops and waits for object to reach it's destination then goes on

#

what's the problem?

vale karma
#

its too leanient with the raycast rn

outer cobalt
visual hedge
# flat slate thanks

I also got an alternative from some source 🙂

IEnumerator DropCoin()
{
    Vector3 position = transform.position;
    GameObject Coin = Instantiate(essenz1, position, Quaternion.identity);
    Coin.SetActive(true);
    yield return new WaitForSeconds(0.5f);

    // Define the speed at which the Coin moves towards the Player
    float speed = 5f;

    // Calculate the direction from the Coin's current position to the Player's position
    Vector3 direction = (Player.transform.position - Coin.transform.position).normalized;

    // Move the Coin towards the Player
    while (Vector3.Distance(Coin.transform.position, Player.transform.position) > 0.1f)
    {
        Coin.transform.position += direction * speed * Time.deltaTime;
        yield return null;
    }
    coin.essenz++;
}

if what works for me won't work for you. Maybee this will. Sorry, haven't tested this one

vale karma
#

i feel like thats exactly what i got goin on already, but in the same script just using a method

#

i got an empty player object at the feet

teal viper
outer cobalt
vale karma
#

as i said it lol, im gonna multiply by 1.5? i think thats gonna work

visual hedge
rare basin
#

to get ready solutions for issues

vale karma
visual hedge
#

I learn things in different ways )

teal viper
rare basin
visual hedge
rare basin
#

and hope you did, to don't spoon feed people ;p

visual hedge
#

😄 ahahah 😄 for damn sure

#

sometimes some stupid problem holds back from doing big things. So IMO I would prefer the person to get stuck learning what's wrong with their huge gameManager instead of being stuck at coin not moving 🙂 Not arguing, just clarifying my standpoint )

teal viper
#

Game development(or any development really) is all about this small things. You can't use a walkaround for everything. And I really doubt you can implement something "big" when you can't even solve small issues.

visual hedge
#

true. But that's a bloody noob speaks in me I guess

rare basin
#

small sidenote 😄

flat slate
rare basin
#

Single-responsibility rule

visual hedge
#

wow... that's strange. Then it's up to pros to help here )

flat slate
#

okay

#

thanks anyway

visual hedge
rare basin
#

i once was revieving an intern and his job recruitment task, and he did entire game logic in a single script Game.cs with almost 4k lines

teal viper
flat slate
#

i do

teal viper
#

It's fine to ask about how things work and why they don't. Do make proper learning too though.

flat slate
#

yea

dapper zenith
#

I have a odd problem trying to get Cinemachine to work, ive used it in the past without problems but i cant seem to get it to work normally at the moment.

i set up a very basic player movement for a 2D game, WASD movement using just GetaxisRaw.

Cinemachine set up 'correctly' with MainCam having the CineBrain and Transform of Player in the Virtual Camera.

If i move around with WASD the Camera will do nothing, but if i drag the character around in the Editor the Camera Follows that... why wont it follow the Character when i move it in game..?

teal viper
dapper zenith
#

Not sure what else to include its incredibly bare bones