#💻┃code-beginner

1 messages · Page 687 of 1

frosty hound
#

For something to happen all the time, and to know when it should stop, something needs to check every frame.

sharp solar
#

in luau we would do it using signals, where Update would be a signal you can connect a function to, is there any similar concept in unity?

frosty hound
#

Whether you doing this yourself, or use some event system, is just a structural thing.

polar acorn
#

If you're not checking it every frame how is it supposed to know it shouldn't do the thing any more

frosty hound
#

Yes, signals in this case would be events I'd imagine.

#

But even that is still checking "all the time" under the hood. You just don't see it, which is probably why you feel better about it 🤷‍♂️

sharp solar
polar acorn
#

You could invoke an event every frame, and just subscribe or unsubscribe from the event but null-checking an empty event and calling them is even more process intensive than checking a bool

polar acorn
sharp solar
#

damn

polar acorn
#

Every other ways is less intuitive and a higher performance cost

#

Checking a boolean is literally a single CPU cycle. It would take four billion of them to take up a second of processing time

sharp solar
#

signals are worse on memory but don't have to check every frame they just run through an array of connected functions every time they are called

polar acorn
sharp solar
#

theres really nothing similar in unity?

polar acorn
polar acorn
#

Why are you so fundamentally opposed to an if statement. It's the single most lightweight operation you can perform in code

sharp solar
#

so if statements are super fast in c#?

polar acorn
#

They're super fast everywhere

#

they map one to one with a machine code instruction

naive pawn
#

if statements are like 3 instructions

sinful jewel
#

Is it even worth nothing to do a complex FSM if the game (2d) is purely for practice?

sharp solar
polar acorn
#

If statements become je or jne

sharp solar
#

but if this is the way then i will do it

polar acorn
polar acorn
naive pawn
#

there would still be the cmp

polar acorn
naive pawn
#

(im being pedantic, of course it doesn't matter)

polar acorn
#

Right, still a fair assessment

sharp solar
#

thank you for the help guys

#

is any kind of dt value passed to Update()

polar acorn
naive pawn
#

no, it's accessible statically ^

sharp solar
#

thank you

#

is delta time constant in unity or variable

polar acorn
#

!code

eternal falconBOT
polar acorn
sharp solar
#

so variable

#

ok wait from a physics perspective should i be using this delta time value

#

or will a force mode of force resolve this?

polar acorn
#

For physics you should be using FixedUpdate and FixedDeltaTime

sharp solar
#

alright cheers

spice mist
naive pawn
#

@sharp solar fyi though - even though going through an array is comparatively slower than doing the direct check, it's still a tiny amount

let's say you have a 2 GHz processor that takes, idk 8 machine cycles for each instruction, being extremely generous
that's 4ns per instruction

an if on a bool would take 3 instructions - load bool, cmp, beq, 12ns
an if on an array would take 6 instructions - load array, load index, add, load value, cmp, beq, 24ns
plus like, 3 more for iteration, load index, add 1, set index, for +12ns

it's 12ns vs 36ns
at 10000 bools, that's 120us vs 360us - still far below a single frame, at 500 fps a single frame is 2ms

naive pawn
sharp solar
#

roblox is such a letdown in almost every regard now that i've seen the light

latent mortar
#

That was my starting language

latent mortar
sharp solar
# latent mortar Real🙏

ive been on it for 4-5 years now and fed up when i ask for a simple bug fix after making them thousands of dollars just to get no response after months of bringing it up then when i say im fed up with not getting a response they remove my post

#

done

latent mortar
#

Wow 4-5 years is pure dedication

thick spoke
#

so i linked between the PlayerCamera class to the class named PotatoMovement(dont mind shitty names i am testing out random stuff). so i think i managed to call the functions correctly. but now i am wondering about the variables, like sensX and sensY. is it possible to add them in PotatoMovement and add SerializeField to them?

sharp solar
#

3-4 years

#

i remember dates wrong

latent mortar
#

Still dedication

fallow wind
#

chat, i copied this from 5 different youtube tutorials, is this good?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed = 5.0f;
    private Rigidbody2D r;
    private float horizontal = 0;
    private float vertical = 0;
    private Vector2 moveDir = Vector2.zero;
    private List<string> moveHistory = new List<string>();
    private bool canMove = false;
    private int frameCounter = 0;
    private string lastKey = "";

    void Awake()
    {
        GameObject obj = GameObject.Find(this.name);
        if (obj != null)
        {
            if (obj.GetComponent<Rigidbody2D>() != null)
            {
                r = obj.GetComponent<Rigidbody2D>();
            }
        }
    }

    void Start()
    {
        StartCoroutine(DelayStart());
    }

    IEnumerator DelayStart()
    {
        yield return new WaitForSeconds(0.00001f);
        canMove = true;
    }

    void Update()
    {
        frameCounter++;
        if (canMove && frameCounter % 1 == 0)
        {
            if (Input.GetKey(KeyCode.A)) { horizontal = -1f; lastKey = "A"; }
            else if (Input.GetKey(KeyCode.D)) { horizontal = 1f; lastKey = "D"; }
            else { horizontal = 0f; }

            if (Input.GetKey(KeyCode.W)) { vertical = 1f; lastKey = "W"; }
            else if (Input.GetKey(KeyCode.S)) { vertical = -1f; lastKey = "S"; }
            else { vertical = 0f; }

            moveDir = new Vector2(horizontal, vertical);
            if (moveHistory.Count > 9) moveHistory.RemoveAt(0);
            moveHistory.Add(lastKey);
        }
    }

    void FixedUpdate()
    {
        if (r != null) r.MovePosition(r.position + moveDir.normalized * speed * Time.fixedDeltaTime);
    }
}
latent mortar
#

I was on it for like 1.5 years

eternal falconBOT
fallow wind
#

sorry, i hit enter too quick

latent mortar
#

Otherwise you won’t retain the information as easily

visual linden
thick spoke
visual linden
#

Nevermind I just saw the Update loop

#

What on Earth

polar acorn
eternal falconBOT
#

:teacher: Unity Learn ↗

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

sour fulcrum
#

the fuck

thick spoke
sharp solar
#

with tutorials just make sure youre working toward something you want and youre not just observing you're trying to come up with your own solution as you go and it's fine

thick spoke
sharp solar
#

watching is bad, doing random tutorials is boring

latent mortar
thick spoke
# polar acorn ` = `

i thought you meant it in smth else, like lets say my main class Player Camera i want to use it on multiple other classes/scripts beside PotatoMovement and i watch each of the other script to have a diffrent value for sensX and sensY. is something like that possible?

polar acorn
polar acorn
# thick spoke yes

Then there's one instance of PlayerCamera. It has a sensX and sensY, which will have whatever value they were last set to

#
int x = 7;
x = 4;
x = 12;
Debug.Log(x);

What do you expect this log to print?

#

It's the same principle.

thick spoke
#

Tysm for the simple explanation

sharp solar
#

what actually are classes

#

this is a new thing to me

sour fulcrum
#

what is an object for you in roblox

sharp solar
#

so same thing?

#

just a thing with properties and methods

sour fulcrum
#

short answer yes

polar acorn
# sharp solar what actually are classes

A class is a blueprint for a thing. It defines the functions, variables, properties, etc. that an object can have.
You can create instances of a class to make an object that uses that blueprint. Those objects are individual elements of that class with their own copies of all of the variables and whatnot.

sharp solar
#

when i put a script inside a game object is it essentially creating a custom component?

#

component whos class is defined by the script

polar acorn
#

Like, a class is "The platonic ideal of Cat". It has variables for name and color and functions for DoMeow() and KnockShitOver(). An individual instance cat is named Ollie and is a Black Cat and when he meows it sounds like a smoker's cough and is an adorable bean

thick spoke
#

i am leaving google at this point, i had a ad tahts 3 minutes long and the video is 9 minutes... so a dd thats 1/3 of the video

polar acorn
sour fulcrum
sharp solar
#

yes

sour fulcrum
#

its a "component" because its inheriting MonoBehaviour which inherits Component which inherits UnityEngine.Object which is the base of class inheritence

sharp solar
#

so it goes without saying unity is very object oriented

polar acorn
#

Most modern programming languages are

sharp solar
#

is there types in c# or just classes

polar acorn
#

Types encompass classes and structs

#

Well, and primitives

sharp solar
#

can you make types

polar acorn
#

Yes, that's what you're doing every time you make a class or struct

sharp solar
#

right ok

#

so turning class code into a type is all automatic

naive pawn
#

no, the class is the type

#

you don't turn the class into the type

sour fulcrum
#

that response sounds like you might have a different thing relating to the term type

naive pawn
#

types include classes, structs, interfaces, enums, delegates, array types, primitives, and generics

sharp solar
sour fulcrum
#

i mean a type is just what something is

naive pawn
sharp solar
#

thats what i meant sorry

sour fulcrum
#

Someone smarter might disagree with this specific wording but its pretty much just an identifier

#

just so you can point your finger at an object and say "thats a human" / "i want a human here"

naive pawn
sour fulcrum
#

yeahh

#

identifier english wise

#

unfortunate overlap?

naive pawn
#

every time dissolve

sharp solar
#

in luau types are more of an optional thing that you use to assist typing out code which is where the confusion lies i think

thick spoke
sour fulcrum
#

imo it's very preferable

naive pawn
polar acorn
thick spoke
naive pawn
#

...by name?

thick spoke
naive pawn
#

what are the errors

thick spoke
#

or do i just write the entire thing

polar acorn
#

That's what the name is for

naive pawn
#

what "entire thing"

polar acorn
#

To serve as the thing you type when you want to use that variable

thick spoke
polar acorn
thin lotus
#

how do I add a value to a list

slender nymph
#

.Add

thick spoke
thin lotus
rich adder
thin lotus
#

list.add?

#

yup, figured it out

thick spoke
thick spoke
rich adder
rich adder
#

the error is on PlayerCam not PotatoMovement

polar acorn
thick spoke
naive pawn
#

that's not what's erroring though

thick spoke
#

@polar acorn @rich adder any more information needed?

polar acorn
naive pawn
#

also don't use deltaTime for mouse input, it's already per-frame

thick spoke
polar acorn
#

The line the error is on

naive pawn
thick spoke
#

i was gonna type that

rich adder
#

ruff

naive pawn
#

that's horrifying

polar acorn
naive pawn
#

welp, what nav said - you never set _playercam

thick spoke
#

i am testing so yeah, my code is really fucked....

polar acorn
#

Don't put two classes in the same file

rich adder
#

wow thanks unity for taking out the error of filename and component not matching..

naive pawn
thick spoke
thick spoke
restive kettle
#

is there any lib i should import for random?

polar acorn
cosmic dagger
restive kettle
polar acorn
thick spoke
#

i got like 5 playcam stuff so i needed to rename one so i can diffrenciate cause i didnt know what was the use of each one

naive pawn
thick spoke
polar acorn
#

But the class is PotatoMovement

thick spoke
polar acorn
naive pawn
#

(they were redirected here)

polar acorn
rich adder
naive pawn
restive kettle
thick spoke
polar acorn
rich adder
#

so you lied

cosmic dagger
thick spoke
naive pawn
polar acorn
thick spoke
polar acorn
#

you have to tell it which PlayerCamera you want that variable to hold a reference to

rich adder
naive pawn
#

assign it in the inspector or use = to set it to something
that might be via GetComponent but we don't know your context to know if that'd be applicable

thick spoke
rich adder
#

in most cases you want to do it in the inspector

naive pawn
rich adder
#

truth

thick spoke
thick spoke
#

but i will try to do it via script

rich adder
#

look up the method they suggested, in the docs then

rich adder
#

here a neat GIF too from unityhuh site

thick spoke
# naive pawn

i meant inside of a script, the get component one 😭

polar acorn
thick spoke
#

so like this?

polar acorn
naive pawn
rich adder
polar acorn
# thick spoke i didnt get it....

This variable is a box. The box has a label on it that says "For FirstPersonMovement.PlayerCameras ONLY! 😠"

You have to actually put something in the box. Which FirstPersonMovement.PlayerCamera do you want to put in the box

thick spoke
polar acorn
#

When you call _playercam.MouseLocking(), which PlayerCamera do you want to call MouseLocking() on

rich adder
polar acorn
thick spoke
thick spoke
polar acorn
thick spoke
#

FirtPersonMovement.PlayerCamera _playercam;
_playercam = GetComponent<PlayerCamera>();

...wrong?

polar acorn
#

FirstPersonMovement.PlayerCamera _playercam is creating a variable that can hold a FirstPersonMovement.PlayerCamera.

_playercam = GetComponent<PlayerCamera>() is setting the _playercam variable to the PlayerCamera component on this object.

#

Does this object have a PlayerCamera component on it

exotic forge
#

and I think instantiating is probably not what you want to do anyway. iirc, instantiating would be to create a gameObject from a prefab that the script sits on. Get component would pick up an existing one off the same game object. new() would be to create an instance of a class that is not a monobehavior. and for monobehaviours... i can't remember the syntax, but there's something like AddComponent<>(). I think

rich adder
exotic forge
#

but in this case, I think what you'd want is to add the PlayerCamera script to the game object in the editor, then use a GetComponent call in PotatoMovement to set your _playercam reference variable

polar acorn
#

Otherwise it's just going to get confusing.

#

Chances are, they do want to do this, but at this point we aren't actually sure what the intent is

exotic forge
#

mhm. fair. I'm just hoping to lay out some definitions at least to help clear things up

polar acorn
#

I'm not sure if they're trying to add a component or reference one that already exists

thick spoke
olive lintel
#

!code

eternal falconBOT
vale turret
#

Hi Guys,
Does unitywebrequest work like coroutine and on main thread? I have to download 6-7 glbs . Not sure if i should use c# native httpClient or unitywebrequest.
I heard UnityWebRequest is executed mainly on main thread.
Dont want to make the game stutter during the downloading (i dont trust coroutine based behaviour for performance while downloading large files paralley)
If i can offload the download to other threads then all good

exotic forge
#

for my web request, I was just using Task / Await which is on the main thread, but it's not a giant download like that, so I can't say how that would go...

#

as far as I know, the job system is the only multi thread option in unity, and it doesn't talk all that well with the main thread, so i'm also not sure how handing over 7 gb as a return type would go

vale turret
#

sorry, its not gb i mean glb format

exotic forge
#

ooooo

#

my bad my bad

vale turret
#

total around 150mb max

#

If i couple HttpClient with UniTask then will that be better?
I feel unitywebrequest use coroutine under the hood.

olive lintel
#

Hey guys, sorry for the stupid question but I'm trying to write a simple function to convert a position from world space to local space in a simplified way that assumes the local space of a logged transform always has a y and z axis rotation of 0. The problem is that I'm having alignment issues with the results and I honestly have no idea how this is happening. It's almost like its assuming the angle of it is slightly off?

    {
        Vector3 localPos = worldPos - origin;
        Vector3 flatPos = localPos;
        flatPos.y = 0;

        return right * flatPos.x + forward * flatPos.z + new Vector3(0, localPos.y,0);
    }

Here's a clip of what isn't working. The Cyan Sphere is the base/anchor transform, and I'm trying to convert the yellow spheres position to its local space. The green line is drawn between what the function above is returning to me and the yellow spheres position.

Any help is greatly appreciated, thank you

shell kernel
#

For probably easy problems with code i just post the code here?

rich adder
exotic forge
#

nice

rich adder
exotic forge
olive lintel
shell kernel
olive lintel
exotic forge
#

ah ok. in that case

#

i will look a little closer at your snippet

#

how are you passing in right and forward?

#

it concerns me that your green line moves when you rotate the cyan sphere

rich adder
shell kernel
#

I want that that button moves my triangle, and it worked, until I added mirrow and suddenly it stoped working

exotic forge
#

mirrow?

shell kernel
#

Oh mirror

#

sorry

rich adder
#

you're doing multiplayer ?

exotic forge
shell kernel
olive lintel
# exotic forge ah ok. in that case

I don't know why, but instead of using the anchor transforms actual transform.forward and transform.right, I create a rotation Quaternion.Euler(0, -anchor.EulerAngles.y, 0) and use the Vector.forward and Vector3.right of that and it works now

#

just switching the Y angle of the anchor seems to have fixed it?

#

*or flipping it

rich adder
exotic forge
#

no it's thedifference bertween using transform.right and vector.right

#

if you comment out he quaternion line, the second one should still work

olive lintel
exotic forge
#

yeah

olive lintel
#

wouldn't testAnchor.forward be the same as testAnchor.rotation * Vector3.forward?

shell kernel
exotic forge
#

ohhhh, I see. maybe. huh....

rich adder
olive lintel
#

I have no idea why it works

#

it makes literally zero sense lmao

rich adder
olive lintel
#

and using -testanchor.forward and -testanchor.right doesnt work either so

#

I have literally no idea why

#

but it works...

exotic forge
#

just out of curiousity, if you only pass in vector3.forward / right without the testRot, what happens?

olive lintel
#

cause its basically assuming the transform has a rotation of Quaternion.identity

exotic forge
#

huh. lol. i'm gonna have to think on that

#

lots of pieces in play, here

golden thorn
#

unity is wholeheartedly convinced that there is a missing script on this object, when it is most certainly there. no other objects named door exist in my scene, and this is the only script the door is trying to reference

anyone have an idea of why it might be doing this?

#

when i click on the script name in the component area of the object it highlights the correct script in the project area, meaning it definitely knows its there.

#

for context, this started as a prefab from the asset store. I removed the old script component on the door, and added a new script component with my own script. It seems like it just wont forget about this deleted script component

gleaming jewel
#

i hate unity

#

its hard asf

#

im thinking about giving up on game dev

#

what should i do

frail hawk
#

what do you find so hard?

hexed terrace
fickle plume
#

!warn 1231260241476456609 Don't spam multiple channels and don't post off-topic. Read #📖┃code-of-conduct . You've been provided with links to resources already.

eternal falconBOT
#

dynoSuccess yaya098009 has been warned.

void thicket
polar acorn
#

And also the prefab

golden thorn
#

here is the parent object (door_1_venge) and its children

#

it is definitely something within this parent/children, i just dont know where

polar acorn
golden thorn
#

door_1_venge is the parent of door.

polar acorn
#

So show the inspector of Door

golden thorn
#

i did

#

the inspector of door is in those images, its the 2nd and 3rd

polar acorn
golden thorn
#

no youre fine, sorry for the image spam there lol. i know discord doesnt make it easy to see

polar acorn
#

Well, this Door object looks to be fine. Is this the prefab, or an instance of it in the scene?

golden thorn
#

may as well add - this is the tree for it

golden thorn
lime sigil
#

heyo i'm working with gltf to load a model into the scene

    private void Import_GLTF()
    {
        string dir = "actual/folder";
        string filename = "file.gltf";

        Uri uri = new Uri(dir);
        string uriString = uri.AbsoluteUri;

        var importOpt = new ImportOptions();
        importOpt.DataLoader = new UnityWebRequestLoader(uriString);
        var import = new GLTFSceneImporter(filename, importOpt);
        Task gltf_import = import.LoadSceneAsync();
    }

this goes on in the background without await so it doesn't stop the user while it's loading even if it's a big model

how would i exactly get the percentage complete from a task?
i can't cast it to Awaitable or Addressable to get that value, how could i approach this in general?

all i could find uses awaitable or addressable and can't cast to either

polar acorn
golden thorn
#

ah it does, so if the original prefab relies on that script, i will get the error even if i removed it on the instance in my scene?

polar acorn
golden thorn
#

yeah so far this is just the initial drop of the door, so i was testing things before making changes to the prefabs themselves

#

lemme see if this fixes it

#

that did, appreciate the help.

#

thatll be an interesting hill to climb when i end up in a situation where I need a one off on a prefab with a different script lol

polar acorn
#

The issue isn't that the prefab has a script that the instance doesn't - it's that something is still expecting that script to be there

#

So, something else is referring to that script, probably within that prefab

shut swallow
#

How do I save player's level completion time and load it in the main menu?

cosmic dagger
eager scarab
#

extremely new to c#, this is the way i was able to make movement but with the addforce thing itll just keep on adding up and build momentum until like infinity pretty sure, so is there any better way i can learn to do this?

#

to any ppl experienced in coding with unity this codes prob gonna look really bad lol

ivory bobcat
eager scarab
#

i was originally gonna change the co ordinates every frame but i just messed around with rigidbodies instead

ivory bobcat
#

If you're wanting to use RB for collision detection the common choices are to:

  • Move using velocity (6.0: linearVelocity)
  • Kinematic RB (create your own physics but still have some RB features - moderate to difficult)
eager scarab
#

i originally tried it with velocity but for some reason it wouldnt move when going to the side, im assuming it has something to do with the colliders

green crater
#

Hello I need some help. I am a total beginner with some coding background but still very much a novice. Trying to add a player movement script to a player object as a component while following a guide on yt. I keep getting this error "Can't add script behaviour 'PlayerMovement'. The script needs to derive from MonoBehaviour!" and am not sure how to troubleshoot.

eager scarab
#

if u made one it should show in brackets on the name in inspector

green crater
eager scarab
#

yea ur gonna wanna click this one

green crater
#

Ah okay I will try that, thank you very much

shut swallow
#

if I wanna save data in relation to a specific scene (e.g. time on stage 1), would it be better if I use dict or using two lists?

ivory bobcat
brave robin
shut swallow
# brave robin Dictionary can't be serialized as-is, so if you play on saving it to JSON or som...

I'm currently following this (https://www.youtube.com/watch?v=XOjd_qU2Ido), would it be better if I do it in JSON and pivot now or is the tutorial still fine

Here's everything you need to know about saving game data in Unity!
► Go to https://expressvpn.com/brackeys , to take back your Internet
privacy TODAY and find out how you can get 3 months free.

● Easy Save: https://bit.ly/2BzgdXb

❤️ Donate: https://www.paypal.com/donate/?hosted_button_id=VCMM2PLRRX8GU

················...

▶ Play video
brave robin
#

I suspect the tutorial is fine, but I don't have time at the moment to watch it all

shut swallow
#

ah ok, it'slike a 6y/o tut, and it made no mentions to JSON so i was a bit confused

brave robin
#

JSON is just one possibility, you can save in many other formats
Just don't save to playerprefs

shut swallow
stuck field
#

PlayerPrefs is fine to use for some saving that isn't a big deal, but most save data, you should avoid it

#

By itself though, not a great utility, if you build a parser for many types and use that to save to playerprefs for non-trivial data, then it's fine

brave robin
#

It has one downfall of being messy. You can always delete files you save in most formats, but playerprefs goes to your registry which is not as simple

stuck field
#

Yeah, definitely more messy, not a preferable option

brave robin
#

Guess that's a new addition since I last looked, as a few years back everyone was writing their own serializable dictionary substitutes that were two lists or structs under the hood

rancid rose
#

I am looking for some pointers on the most appropriate way to avoid my player (rigidbody) getting stuck on walls in my 3d scene. I've tried setting the walls friction and bounciness to 0, and this has stopped my issues with getting stuck, but has introduced weird movement with steep slopes where the player is able to walk up slopes they definitely shouldn't be able too. Is there other solutions to the problem that fix the player getting stuck on walls without breaking slope movement?

wind hinge
#

How do you make a custom cursor with special vfx without it lagging behind?

shut swallow
#

FindObjectsOfType<MonoBehaviour>() how do I rewrite this with the new FindObjectsByType, I just replaces Of to By and it didn't work

#

what do I pass as object?

shell sorrel
#

looking at the docs you need to pass it the sort mode to use

#

FindObjectsSortMode.None

shut swallow
#

what's the syntax, I'm reading the api and still a bit confused

shell sorrel
#

pass the type as a generic so in the <>

shut swallow
shell sorrel
#

FindObjectsByType<MonoBehaviour>(FindObjectsSortMode.None)

shut swallow
#

I thought type needed to be declaired within the method

shell sorrel
#

it supports both

#

but using generics is better since you get the proper return type without a cast

#

to pass it as a args you need to use typeof

#

FindObjectsByType(typeof(MonoBehaviour), FindObjectsSortMode.None)

shut swallow
#

any reason to use args over the generic?

shell sorrel
#

for 90% of cases or more no

#

use the generic

sour fulcrum
#

weird and probably unideal situations where your passing through a type via a param/value and can't explicitly define the generic usage

shell sorrel
#

doing it via args can make sense in some edge cases

#

like if you got a type via reflection

#

for most cases if something needs a type and supports generics use that over passing it as a regular arg

sour fulcrum
#

Also not directly saying don’t do it that way but findobjectoftype calls are pretty heavy and iterating through every monobehaviour conditionally casting is probably not great either at scale

shell sorrel
#

99% chance you are better off doing the reverse of this, having those objects call a manager and pass themselfs to it

sour fulcrum
#

And if for whatever reason these objects toggle their gameobject activity that search won’t find them unless you specify in the findobjectsoftype param that you wanna find inactive objects

shell sorrel
#

then you get a collection that only contains stuff you care about without searching every component in the scene

sour fulcrum
#

I guess that's somewhat by design but

shell sorrel
sour fulcrum
#

fair, i just meant that the component has to explicitly handle the giving that out

shell sorrel
#

yeah its that or searching alot of objects

#

i very commonly have things that on Start will notify other systems about themselfs oftne just calling a method and passing this

#

and due to covariance it will work even if its accepting it via interface

sour fulcrum
#

yeah same. I think i keep wanting interfaces to do stuff there not meant to do and i get dissapointed when they cant aha

#

would be "nice" to get a interface function running on object creation without needing the thing implementing it to "manually" call it

shell sorrel
#

they do most things i want, only rubbish part is not working with SerialzeField

#

but i also don't really use components unless i have to, so a lot of systems are just regular C# with regular objects

sour fulcrum
shell sorrel
#

yeah i do not use default implementations for the most part, feels like fighting what interfaces really are

sour fulcrum
#

probably

shut swallow
#

idek what's an audio listener, how do I solve this

sour fulcrum
#

usually they on cameras iirc

queen adder
rancid rose
rich ice
#

and special vfx

#

assuming it's just an image then just setting the image's position to the mouse position in update should work fine (i dont think it'd lag behind a by a frame but im not 100% sure)

sharp solar
#

is garbage collection automatic in c#

rich ice
#

i've never worked with garbage collection but this might be a good place to look

sharp solar
#

why does unity have to use quaternions 😢

#

3x3 matrix is so much awesomer

rich ice
#

reminds me i also need to look into quaternions some more. i still barely understand them UnityChanDown

sharp solar
#

im hoping through functions i wont have to understand them lol

formal tide
#

I finally added 5 second cool down after using jump

sharp solar
#

is there any difference between Awake() and Start()

formal tide
#

Awake has priority on execution order

#

I learned this today 😁

sharp solar
#

can you access unity hierarchy through a script during runtime instead of setting public variables beforehand

rich ice
rich ice
sharp solar
#

oh ok

formal tide
#

But i dont wanna push too fast. tho i should practice what i learn recently

rich ice
#

usually you'd have a script as a component on an object and then you could reference the script in the editor by passing in the component.
i discovered UnityEvents pretty recently though and they've been so useful (UnityEvents my beloved)

rich ice
eternal needle
eternal needle
sharp solar
#

true

formal tide
#

U can learn everhthing with these 3

#

Just be aware that ai can give u wrong answers sometimes

#

U need to check documentation first then ai to see the end of tha road mate

#

😁

#

😧

sharp solar
#

formal tide
#

I learned everything with tha ai and unity documentation bruv

sharp solar
#

yea

formal tide
#

I tried youtube and udemy but it didnt worked for me

sharp solar
#

youtube sucks

#

u learn how to make the thing they are making but u dont learn how to use unity

#

(that was my experience with roblox lol)

formal tide
#

Sometimes works. If i didnt understand with ai and documentation i go google and youtubr

#

Last chance

sharp solar
#

AI is pretty cracked nowadays

#

wasn't really a thing last time i had to learn something

formal tide
#

Ai doesnt give me the full answer most of the time on coding

#

I have to edit it

#

But ai shows u the road very well

#

About which techniques u should use

#

Maybe im wrong but i feel like it works 🤣

glad ibex
#

Ai is good for learning unless you just mindlessly copy and paste

formal tide
#

At least it gives me the different solutions and see the different routr

#

Route

sharp solar
#

just dont ask AI to write you the code

#

boom

eternal needle
#

a bunch of beginners telling each other AI helped them learn definitely isnt the best advice you want to be reading from.

sharp solar
#

am only a beginner to unity***

formal tide
#

I rather use ai than a university student acting like he is computer engineer professor

eternal needle
ivory bobcat
# glad ibex Ai is good for learning unless you just mindlessly copy and paste

A couple of reasons why AI isn't good to learn from:

  • It makes mistakes that you may be unaware of
  • It uses strange patterns and do not really understand what it's doing
  • It's convincing
  • It lies
  • Dependency issues
    A couple of reasons why AI might be useful:
  • Pretty up code you've already written (documentation, syntax etc)
  • Draft prototypes that are tedious to write
    Personally, I'd use it like a work horse to brute force simple tedious tasks.. if anything.
    It's not very fun to fix mistakes that aren't relevant and can lead a beginner down the rabbit hole if they aren't aware that it's wrong/lying.
burnt vapor
#

It takes a specific mindset to actually learn from AI, and most people don't have it in them to actually understand what is written and how it is written, especially here.

#

And also because it can be confidently wrong, meaning you need to ensure that your knowledge and/or research skills is good enough to understand if the code is good

eternal needle
#

It's all too common where a beginner will see any positive feedback about AI and decide to continue using it for everything regardless of how many negatives you list.
Though the worst is the case above where a beginner who clearly started recently says they learned everything through AI. "Everything" being very misleading when they said they don't know how to reference another script.

formal tide
#

even professional coders uses it

#

no need to avoid it

#

its useful sometimes but yea it can give u wrong answers

eternal needle
formal tide
#

and i told you that ai can give u wrong answer and u need to edit it

eternal needle
#

As i pointed out above, there is also a forum for AI discussions

rich ice
# formal tide i recommend ai

it's a debatable question. AI is still a very new thing and it's still at the point where it's improving by the day.
imo it's just down to personal preference although solely relying on it is definitely going a bit too far. using the general standard is usually the safest bet and thus the only one you can really recommend.

eager spindle
# formal tide is it forbidden to recommend ai

yes, this discord server is for learning and AI is not good for learning at all. people who use AI for learning will lean in to just having AI code everything for them, and they won't develop the skills to research what they're looking for and debug code, the most important parts of being a developer

#

when you go out to work you realise that you won't know everything, and you'll be using libraries that just have next to no documentation. your AI won't be able to help you anymore and you're expected to live without AI

formal tide
#

im using unity doc ai youtube google

eager spindle
sharp solar
#

this is a silly conversation

eager spindle
#

it's actually painful

#

let's not promote AI here at all

formal tide
eager spindle
#

so you don't wanna learn coding and just have us debug for you

sharp solar
#

people here are going to naturally gravitate toward pro AI or anti AI mindsets and whether you should or shouldnt use AI is highly opinionated. just do what you want, it's a tool, no need to push your beliefs onto others

formal tide
burnt vapor
eager spindle
#

if you don't work in a programming role then ok I guess but just try to understand what the AI is giving you

burnt vapor
#

We're not against AI, we don't need people suggesting AI to beginners because it won't work for them

eager spindle
#

this channel has been flooded with people asking us to debug their AI generated code

formal tide
#

in my own experience. i tried to learn coding in the past too much and i always failed and i gave ai chance and i liked it with the help of unity documentation

north kiln
#

I'd rather eat bricks personally, but you do you

eternal needle
eager spindle
#

It's just not nice to ask other people to fix code when the person doesn't even know the fundamentals of coding

formal tide
burnt vapor
eager spindle
burnt vapor
#

They come here, often after many failed attempts of editing the code and making it worse

north kiln
#

If someone says they used AI and have come here for help it's a great invitation for me to do something worthwhile elsewhere

formal tide
#

i dont copy paste code without understand it. im searching on unity documentation youtube google to see if its logical

#

if its logical i copy paste it

eager spindle
#

That's good

#

Do try to understand the code along the way

formal tide
#

for sure

#

i analyze codes that ai recommends

#

i should give disclaimer before

sharp solar
eager spindle
fickle plume
#

@formal tide Trying to learn from pre-chewed responses of LLM is very counterproductive. By not looking up things in documentation and using structured courses you are severely handicapping yourself.
But that's up to you.
Here, like you've been told already, don't send people to AI or talk about it really, it's off-topic.

sharp solar
#

pasting a block of code and saying "fix it" is annoying in general in my opinion

#

this happened before AI too

formal tide
#

i use all of em

#

jesus

fickle plume
formal tide
#

i didnt know ai was hot topic like this

rich ice
sour fulcrum
#

more specifically the dogpilling was more so in response to the endorsement of ai rather than acknowledgement of usage

golden obsidian
eager spindle
#

and more that the user is suggesting that beginners can rely on AI to teach them things without developing developer skills is a bad idea in general

visual linden
# formal tide i didnt know ai was hot topic like this

Most of us here are volunteering our time helping others, and picking up where AI left off with people who aren’t actually interesting in learning rubs most here the wrong way.
It’s nothing super specific to AI as much as it is trying to respect people’s time and effort. Presenting a problem is different from presenting incorrect AI replies asking what’s wrong with it.

formal tide
#

yep u shouldnt rely on ai. always use unity documentation as a source and then u can use other sources as well 😄

north kiln
#

To me it's just an insulting thing to suggest as a starting place in a place full of developers who spend their own time here helping others.

eternal needle
fickle plume
#

Not to mention, stuff you get from LLM is the average terrible code it scraped that you are learning from.

formal tide
sharp solar
#

what type of question can you even ask here that isnt easily googled anyway

#

in the beginner channel

eager spindle
#

Then tell them to Google it next time

#

spoonfeeding sure but they need a head start

visual linden
north kiln
#

Often the problem is they haven't developed the knowhow to know what to look for and need a push in the right direction

shut swallow
#

does saving a dict to JSON not need any extra steps now?

eager spindle
#

I don't like when the top answer of a forum is just telling others to Google it or linking to another page without elaboration, top searches get rearranged over the years and forums can get deleted.

Speaking from personal experience when messing with Playfab, it got bought over by Microsoft and they deleted the old forums entirely

eager spindle
eternal needle
shut swallow
eternal needle
#

Np, was saying it more as a reminder

sharp solar
#

because you have to recreate an array every time its resized, is an array still the correct thing to use for a list that resizes all the time?

#

or is there a better way

eternal needle
sharp solar
#

a list is just a resizeable array right

eternal needle
#

It just handles the logic for you, you can treat it as a resizable array

eager spindle
#

Not as related but if you really want to optimise your list so much you can also look into object pooling

#

Otherwise, sticking to a list/making your own logic for a resizeable array is just fine

eternal needle
burnt vapor
#

Also, if you want to avoid constantly reallocating an array to fit the new size, a List just hides this and doesn't make it any better.

#

Allocate an array that is big enough for your use case, or consider handling it in batches based on what fits and handle the rest the next round.

#

This is also why Unity provides the ability to pass arrays into various methods because you allocating it once is a lot better than Unity constantly making one when you call the method

cosmic dagger
#

is it possible to make Unity not use GPU at all for rendering and only use CPU?
for context, before i had issues with my nvidia drivers not being detected and Unity was running CPU-only, which was.... bearable but still too slow. i updated and fixed the drivers and they are running well now. now i am trying out an asset (Crest) and i encounter visual glitches, and they might be caused by the drivers being funny. i want to see whether it's the asset or the drivers that are at fault.
so my question is whether I can go back to that CPU-only state without completely turning off the drivers for my entire PC?

#

i looked it up online and it seems like it's super nonstandard and most forums suggest -nographics which turns off the display of the entire editor but that is not my goal

visual linden
cosmic dagger
#

aha i see, that would make sense, let me try

sharp bloom
#

I don't understand how unsubscribing from events work.
If have I have an arrow function like OnSomethingHappened += () => {DoSomething();};, do I need to unsubscribe? And how would I do that?

#

I just found out my scene breaks when I reload...I think it's because I haven't unsubbed to any events

rugged beacon
#

!code

eternal falconBOT
rugged beacon
#

@sharp bloom its for me

rich ice
visual linden
# sharp bloom I don't understand how unsubscribing from events work. If have I have an arrow f...

What you're doing there is creating an anonymous delegate that then calls your DoSomething function.
What you want to do is something like OnSomethingHappened += DoSomething();, that way you can unsubscribe later on with OnSomethingHappened -= DoSomething();.
Here's a good resource on the topic
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/delegates-with-named-vs-anonymous-methods

rugged beacon
sharp bloom
#

If that in itself is a type of delegate?

shut swallow
#
    {
        data.timeElapsed = Mathf.Min(data.timeElapsed, this.elapsedTime);
        data.gameTimeElapsed = Mathf.Min(data.gameTimeElapsed, this.gameTime);
        if (levelCompleted && data.timeElapsed > this.elapsedTime || data.timeElapsed == 0)
            data.levelTimeTracker.Add(id, elapsedTime);
    }```how could I rewrite this so I can actually store the least amount of time it takes for a player to complete a level? Right now all I get in my json file is zero
frigid sequoia
#

Hey, how could I like... make some kind of event system where I calculate a value and then send a call to see if there is anything extra that would like to modify that value?

#

Like, imagine a method that makes an attack, so it calculates the damage of it, but the character has an item that goes like "your attacks do magic damage instead"

#

Like, I cannot really handle that with events can I?

shut swallow
sharp bloom
# sharp bloom So if I I understand correctly, if the event is `System.Action` type, was the a...

Okay, so I have changed this

ClockScript.OnSecondsChanged += (int context) => 
{
    tickTimer += 1;
    if (tickTimer >= 20)
    {
        tickTimer = 0;
        EndTurn();
    }
};

into this

ClockScript.OnSecondsChanged += TurnEnderEventHandler;

private void TurnEnderEventHandler(int seconds)
{
    tickTimer += 1;
    if (tickTimer >= 20)
    {
        tickTimer = 0;
        EndTurn();
    }
}

private void OnDisable()
{
    ClockScript.OnSecondsChanged -= TurnEnderEventHandler;
}
#

I think now it's getting unsubscribed correctly

visual linden
restive kettle
#

guys if i wanna change the cupe color in c# i saw someone using cube.getcomponet<Render>

#

but the vsc aint suggesting it to me

hexed terrace
#

"it" - what isn't it suggesting?

hexed terrace
#

cube is a mesh, your IDE doesn't know what that is. It also can't have a component, they go on GameObjects.

You need to create a GameObject variable, assign the thep to it and then GetComponent will work

#

Unless of course, you created the var as cube then it's just what halfspacer said

shut swallow
frigid sequoia
sharp bloom
#

Where should I call this?

naive pawn
sharp bloom
naive pawn
#

perhaps not a fix for the issue, just a sidenote

shut swallow
#

should I just make inital value very large to fix this?

frigid sequoia
naive pawn
#

using 0 is a fine default value imo - a flag for "no value"

shut swallow
#
    {
        if (levelCompleted && data.timeElapsed > this.elapsedTime)
            data.timeElapsed = this.elapsedTime;
            data.gameTimeElapsed = this.gameTime;
            data.levelTimeTracker.Add(id, elapsedTime);
    }```Yea this seems to make a lot more sense
naive pawn
#

you're missing braces there

frigid sequoia
shut swallow
#

quick question, when I store the key-value pair into the dict, how would I replace the {id, elapsedTime} with the shorter version?

hexed terrace
#

dictionary[key] = newValue;

naive pawn
#

[id] = elapsedTime?

shut swallow
hexed terrace
#

You'll need to check for the key first

naive pawn
shut swallow
#

noted

eager scarab
naive pawn
#

!code

eternal falconBOT
naive pawn
#

have you tried doing some debugging to check if it's being picked up?

eager scarab
naive pawn
#

could just Debug.Log($"A: {Input.GetKey(KeyCode.A)}, D: {Input.GetKey(KeyCode.D)}");

eager scarab
#

both inputs are being read

naive pawn
#

when you only press A?

#

oh wait you're clamping the speed so it's only ever positive lmao

eager scarab
#

that would make sense why its not working then lol

#

what would be a better way to go about with the calculations

#

i made someone elses code my property to make it and planned to get it working then lookup any details i dont know to slowly increase my knowledge based off things that worked but it seems that i probably should do a little bit of looking up before hand

lusty star
#

it keeps not adding whitespaces, yes i checked the settings

eager scarab
#

thx

naive pawn
eager scarab
#

yea that works but ill do the way chris said since only one variable needed

shut swallow
#

do I directly get values from a dict by levelTimeTracker.TryGetValue(Id, out var value) given some {Id : value} pair?
do I need to define the type of value being outputted or does it just output whatever the associated value is?

naive pawn
#

var means the type is inferred. if it weren't inferrable, you wouldn't be allowed to use it there

shut swallow
#

levelTimeTracker.TryGetValue(Id, out float value) something like that

naive pawn
#

you can hover over the variable to see what its type is

naive pawn
#

check in scene view to see if anything is overlapping it and check if the text in the component is correct

warped pendant
naive pawn
#

maybe, i think #📲┃ui-ux would be more suited to help with this

warped pendant
#

ok. ty for the response

shut swallow
#

public class FinishFlag : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.tag == "Player")
        {
            GameManager.Instance.UpdateLevelCompleted(true);
        }
    }
}``` I attached this script to 3D worldspace UI element but somehow no collision came up
#

both the player and the flag has a collider, with the flag being trigger

naive pawn
#

Thinkeng not sure physics and recttransforms will play nice with each other

shut swallow
naive pawn
#

what other way around?

shut swallow
#

on trigger enter on the player getting the tag of the falg

frosty hound
#

If this is just for the flag, you should be using a sprite renderer, not UI.

#

(Not that it changes the physics)

naive pawn
#

it's the physics check that I don't think would work properly

shut swallow
#

why tho?

naive pawn
#

anyways, the player has a rigidbody, right?

naive pawn
shut swallow
naive pawn
#

well, that'd be why

#

physics are driven by rigidbodies

shut swallow
#

ahh

naive pawn
#

...wait kcc doesn't use rbs?

#

i thought it did, but i didn't really look into the actual package

shut swallow
#

I think it's a toggle

#

I just looked at the panel now that you mentioned it

#

and there's a rb interaction type

naive pawn
#

why is your flag a ui element anyways

shut swallow
#

idk, it's just a visual element in worldspace so I figured just to use ui

shut swallow
#

ok adding a rb worked

#

ok one more question

#

how do I make sure Timer gets to save the data before TimeDisplay pulls from the JSON file?

#

also, why is the dict not saved within the JSON?

#

I checked my files and the dict is just not there

teal viper
valid violet
#

There is trick how to serialize dictionaries with lists

naive pawn
shut swallow
naive pawn
#

you're introducing some really unneeded complexity

teal viper
shut swallow
shut swallow
teal viper
shut swallow
#

oh uhh is it this

teal viper
open apex
#
{
    //This is to handle how much velocity we want to add to the cube/it's speed
    public float speed = 10;
    //This is for debugging purposes, making sure everything works fine
    public Text textMessage;

    //Getting buttons
    public GameObject leftButton;
    public GameObject rightButton;
    //Getting/accessing the script within the button, you just assign the button and it reaches the "HoldButtonHandler" script within it, so you basically don't have to do anything
    public HoldButtonHandler leftIsHolding;
    public HoldButtonHandler rightIsHolding;

    //Getting the cube and it's rigidBody
    public GameObject theCube;
    Rigidbody2D cubeRigidBody;





    private void Awake()
    {
        //Getting the rigidbody of the cube
        cubeRigidBody = theCube.GetComponent<Rigidbody2D>();

        //Getting the isHolding variable details for the left button (and the same for the right button)
        leftIsHolding = leftButton.GetComponent<HoldButtonHandler>();
        rightIsHolding = rightButton.GetComponent<HoldButtonHandler>();

    }

    
    void FixedUpdate()
    {
        if (rightIsHolding.isHolding) 
        {
            int x = 2;
            textMessage.text = "You pressed the right button";

            cubeRigidBody.velocity = new Vector2(x * speed, cubeRigidBody.velocity.y).normalized;
            //cubeRigidBody.AddForce(Vector2.right * velocity, ForceMode2D.Impulse);
        }
        if (leftIsHolding.isHolding) 
        {
            int x = 2;
            textMessage.text = "You pressed the left button";

            Vector2 direction = new Vector2(x, cubeRigidBody.velocity.y).normalized;
            cubeRigidBody.velocity = direction * -speed;
            //cubeRigidBody.AddForce(Vector2.left * velocity, ForceMode2D.Impulse);
        }
    }
}

I am confused at the last part, when I do cubeRigidBody.velocity = direction * -speed; the player moves faster compared to x * speed

#

Can anyone explain please?

#

This is a player movement script

#

I understand 90% of my code only, the rest doesn't make much sense to me either due to shit tutorials

valid violet
open apex
naive pawn
#

that one isn't for you

steel smelt
#

They weren't talking to you

In the right side check, you multiply by speed prior to normalization. In the left side check, you normalize and then multiply by speed

naive pawn
valid violet
#

@open apex you normalizing vector after speed was aplied your actual speed is changing vector direction instead of affecting actual speed

open apex
# naive pawn what scenarios are you comparing, exactly?

I don't undestand what you mean.But here is an explanation, basically I am trying to add player movement to my character, I have decided to use velocity and to adjust how fast the player moves I have given it a variable called speed. What I did was "cubeRigidBody.velocity = new Vector2(x * speed, cubeRigidBody.velocity.y).normalized;" no matter how high "speed" was the cube wouldn't move faster, so I looked up at a tutorial, they did " Vector2 direction = new Vector2(x, cubeRigidBody.velocity.y).normalized;
cubeRigidBody.velocity = direction * speed;"

instead it start to move just fine but I don't understand how, is as foo mentioned because it was normalized? If I remember correctly when normalized the max value of the variable would 1 or -1 (?)

naive pawn
#

normalization of a vector makes its magnitude 1

#

for a vector2, that means sqrt(x*x + y*y) = 1

open apex
#

Owhhh

valid violet
#

You need rb.velocity = direction.normalize*speed where direction is Vector2

naive pawn
#

if this is supposed to be a sidescroller context with gravity, then you don't need to normalize the vector at all, since that'd be affecting gravity

open apex
#

I am not exactly sure why I would need to normalize it either as it's just 1 and -1, I just do it because it's "good practice"

naive pawn
#

you don't need to normalize in this scenario

#

in this context, normalization would be done to turn some x/y values into a direction, with magnitude 1
in a top-down game, if you press W and D and turn that into a vector, that would be (1, 1), which is actually going faster than going only right or going only up, so normalization would make the magnitude, and thus overall speed, uniform

but your code seems to indicate you're in a sidescroller, so you don't need anything like that

open apex
#

UI

naive pawn
#

i'm giving an example

grand snow
#

wow 😐

open apex
#

Ohh ok

valid violet
#

@open apex Normilzed make vector Magnitude equal to 1 not X and not Y the lenght of vector so if u want ur player move with speed 5 you normalize the vector coz in else case vector magnitude can have length 10 or .3 and speed will not be 5

naive pawn
#

damn use some punctuation 💀

open apex
#

but I understand what he means

grand snow
#

Its useful for many things e.g. get direction from a to b, normalise and then scale to new desired length with ease

eager scarab
#

how would I go about detecting if the character is on the ground (2d, im using capsule collider 2d and rigidbody 2d on the player)

open apex
#

I love programming, I've got very little to no idea what I'm doing and I'm going of based off of theory and a bit knowledge, if something doesn't work = research, if it does = understand how it works and keep on moving

eager scarab
naive pawn
jolly stag
#

I was wondering if anyone was free to help me with something? I'm having issues getting collision to work, it's supposed to hit something with the tag "Power Up" and then destroy itself but it's not recognising it and won't hit it. I have a collider and Rigidbodys on both objects.

valid violet
#

Did you set the tag of target?

jolly stag
naive pawn
valid violet
naive pawn
#

also, is the powerup a trigger?

jolly stag
jolly stag
naive pawn
#

then there wouldn't be a collision

#

use the trigger message

#

make sure to update the parameter type as well, they have different signatures

jolly stag
#
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    public int bulletSpeed = 5;
    private float bulletRange = 10.0f;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(new Vector3(0, 1, 0) *bulletSpeed * Time.deltaTime);
        if (transform.position.z > bulletRange)
        {
            GameObject.Destroy(gameObject);
        }
    }
    private void OnTriggerEnter(Collider other)
    {
        if (CompareTag("Power Up"))
        {
            Destroy(gameObject);
            Debug.Log("Hit");
        }
    }
}```

I am using OnTriggerEnter
naive pawn
#

CompareTag there would be checking the tag of the current GO

#

"bullet" doesn't seem like it'd be the same object as the powerup, so you probably want to check the tag of other

jolly stag
eager scarab
valid violet
#

use this instead CompareTag is doing nothing ````if(other.tag=="Power Up")```

eager scarab
#

also are tags for colliders gonna be useful to differentiate like a wall from the ground, so i cant just wall bounce alot

naive pawn
#

you can use the CompareTag just fine, doesn't need to be a tag comparison - just needs to be on other

jolly stag
naive pawn
jolly stag
#

That makes sense, Thank you!

valid violet
#

You need to do other.gameObject.CompareTag("Power Up")

eager scarab
naive pawn
#

you don't need the intermediate .gameObject

naive pawn
valid violet
#

What do you mean it cannot work such way it is not possible CompareTag("Power Up") this code is 100% uncorrect

naive pawn
#

didn't say it was

jolly stag
naive pawn
#

other.CompareTag("Power Up") and other.tag == "Power Up" are both fine
.gameObject is unnecessary

valid violet
#

I didn't remember if collider have field tag so used gameObject to be sure it will works

#

you are right there

grand snow
#

CompareTag() is better to avoid a string allocation

naive pawn
#

only with a taghandle, no?

grand snow
#

Hm? CompareTag() doesnt need to allocate the tag string in managed memory for the comparison.
Should be why CompareTag() even exists

#

anyway bit much to think about for beginners

naive pawn
#

(im curious about the internals of what was done there)

grand snow
naive pawn
#

ah, cool

#

(checking my understanding) so it's not the == vsCompareTag that's optimized, it's the removal of .tag that's better?

grand snow
#

Yea, string comparison is done either way but one is a tad better.

#

And ofc TagHandle exists to further improve things

eager scarab
#

im thinking i could do the 2 ifs in a if and elseif based on diff languages ive used but idk if thatll be true for this

eternal falconBOT
naive pawn
#

you could just do _Grounded = hit; though

shut swallow
#

for savedata to check data, do I need to load it first?

    {
        data.levelTimeTracker.TryGetValue(SceneManager.GetActiveScene().name, out elapsedTime);

    }

    public void SaveData(ref PlayerData data)
    {
        if (GameManager.Instance.levelCompleted && data.timeElapsed > this.elapsedTime)
        {
            data.timeElapsed = this.elapsedTime;
            data.gameTimeElapsed = this.gameTime;
            data.sceneID = SceneManager.GetActiveScene().name;
            if (data.levelTimeTracker.ContainsKey(SceneManager.GetActiveScene().name))
            {
                data.levelTimeTracker.Remove(SceneManager.GetActiveScene().name);
            }
            data.levelTimeTracker.Add(SceneManager.GetActiveScene().name, elapsedTime);
        }
    }```
valid violet
#

@eager scarab optimization looks fine

jolly stag
naive pawn
eager scarab
naive pawn
#

_Grounded = hit.collider != null; would also work

#

also fyi for the future, else exists

naive pawn
eager scarab
naive pawn
#

yeah pretty much every language uses if and else

eager scarab
naive pawn
#

the differences are in else if vs elif vs elsif, and then/fi/end

naive pawn
# eager scarab thanks, didnt know hit was already a boolean

it isn't, it has an implicit boolean conversion - it can be treated as if it were a boolean

// Implicitly convert a hit to a boolean based upon whether a collider reference exists or not.
public static implicit operator bool(RaycastHit2D hit)
{
    return hit.collider != null;
}
shut swallow
#

But I have a bigger problem here apperently

#

there's no saving values

#

I've serialized the dict properly now but it seems like I can't save my data

regal magnet
#

what is the best way to add dialog system to my 2d unity game? i saw tons of video with different ways which one is your fav?

naive pawn
hexed terrace
#

buy an asset 😄

rich adder
#

Ink is a good system and is free

#

Comes with its own markup you can easily interact mid dialaugue and branches

regal magnet
shut swallow
rich adder
naive pawn
#

it's saving to PlayerData, but it's not actually statically saving anywhere else? (to network/to disk)

#

what is your save system?

#

you're leaving a lot to be assumed

regal magnet
shut swallow
#

https://www.youtube.com/watch?v=aUi9aijvpgs I'm following this tutorial but to paraphrase it it's saving to a data persistence manager, where the singleton saves a snapshot of the data to store it in json

In this video, I show how to make a Save and Load system in Unity that will work for any type of game. We'll save the data to a file in both a JSON format as well as an encrypted format which we'll be able to toggle between in the Unity inspector.

IMPORTANT: For WebGL games, because WebGL can't save directly to a file system, a different meth...

▶ Play video
rich adder
regal magnet
shut swallow
rich adder
hexed terrace
shut swallow
# hexed terrace ~~Nothing there saves to a json.~~ (I missed the tabs) It just adds data to a di...

I missed a script, I have

using UnityEngine;

[System.Serializable]
public class SerializableDictionary<Tkey, Tvalue> : Dictionary<Tkey, Tvalue>, ISerializationCallbackReceiver
{
    [SerializeField] private List<Tkey> keys = new List<Tkey>();
    [SerializeField] private List<Tvalue> values = new List<Tvalue>();

    public void OnBeforeSerialize()
    {
        keys.Clear(); 
        values.Clear();
        foreach (KeyValuePair<Tkey, Tvalue> pair in this)
        {
            keys.Add(pair.Key);
            values.Add(pair.Value);
        }
    }

    public void OnAfterDeserialize() 
    {
        this.Clear();

        if(keys.Count != values.Count)
        {
            Debug.LogError("Deserialization error, key-value mismatch.\nKey : Value " + keys.Count + " : " + values.Count);
        }

        for(int i = 0; i < keys.Count; i++)
        {
            this.Add(keys[i], values[i]);
        }
    }

}```
shut swallow
foggy crypt
#

Guys, any advice on how to make Transform.Translate get the Vector3 once, and move in that direction, even if the direction changes?

hexed terrace
naive pawn
naive pawn
rich adder
naive pawn
#

if you want to apply a translation that doesn't care about the rotation, you can set Space.World or add to the position directly

foggy crypt
#

I figured it out 🙂

rich adder
#

newtonsoft > JsonUtility

sour fulcrum
#

not that it's a direct solution but might even just be worth turning that dict into a serializable struct or something in the event you want more data in there too

#

in some situations maybe "overkill" but if your making a whole save thing anyway

rich adder
#

one thing newtonsoft has weird issue with Vector3. not sure if thats still a thing but you have to disable "self-referencing loops " or whatever the option was

naive pawn
#

what, for like normalized or something?

eternal needle
rich adder
#

but you just add cs JsonSerializerSettings settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; I think and it goes away

shut swallow
naive pawn
# rich adder yea

why would it serialize properties rather than their backing fields Thinkeng

shut swallow
rich adder
shut swallow
#

unity cloud strikes again

rich adder
rich adder
eternal needle
#

I'm not sure about this whole cloud aspect of it or what you can or can't do there tbh

#

Could be valuable even just seeing how they handle it in the package I linked, if that helps for your case

shut swallow
rich adder
# eternal needle I'm not sure about this whole cloud aspect of it or what you can or can't do the...

basically you save

        var playerData = new Dictionary<string, object>{
          {"firstKeyName", "a text value"},
          {"secondKeyName", 123}
        };
await CloudSaveService.Instance.Data.Player.SaveAsync(playerData);```

But if you pass a serialized object in `object` like a struct that contains Vector3. you get the same error i mentioned earlier about newtonsoft self-referencing loop thing but you cannot change anything since its on unitys server side of things
I just ended up making my custom `Position`(3floats) like vector3 anyway but still
I have a Vector3 to Position converter and vice versa
sour fulcrum
shut swallow
rich adder
sour fulcrum
#

Yeah I always get worried about direct generics not doing serialization related stuff well since unity object classes dont like it

#

without defining them in a inheriting type

#

i have a generic INetworkSerializable struct i still gotta test

naive pawn
rich adder
valid violet
#

object class is created by Microsoft for Companies to ask about it on the Interview )

shut swallow
rich adder
shut swallow
rich adder
shut swallow
#

and also, how can I fix this?

rich adder
#

You are able to fix it if you narrow down to the cause

shut swallow
#

I just could not call it

rich adder
#

not sure what you mean by that

shut swallow
#

on my display script

shut swallow
#

but I couldn't call it

rich adder
#

I still don't know what you by "couldn't call it "

#

calling what

shut swallow
sour fulcrum
#

loading?

shut swallow
#

yea

#

loading

rich adder
#

De serializing

#

If it's saving the data then loading isn't any different

rich adder
shut swallow
#

yes

#

my singleton could see the new value

sour fulcrum
#

save values

#

did the values from the dict save

shut swallow
#

yea

#

all values looks right

rich adder
#

so which part isn't working lol

shut swallow
#

the part where I wanted to get the value and display it

rich adder
sour fulcrum
#

does updatetext run after loaddata

shut swallow
#

so it should show

shut swallow
sour fulcrum
#

it needs to 😛

shut swallow
sour fulcrum
#

well

#

run it in loaddata after you set besttime

#

see if it works

shut swallow
willow iron
#

Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
so got this vector3 from the A* pathfinding algorithm. I already have a way to smoothly rotate my 2d gameobject towards the vector using slerp, but i also have a mesh that i wish to rotate towards this direction. plugging in my transform directly doesn't work as it simply flips left and right instead of actually rotating.

simpily put, i want to rotate towards this vector3, but gradually instead of all at once. any tips?

shell sorrel
#

depends on how you want to do it

#

does it move to one point to the other with a fixed speed or a fixed duration

#

normally most would just use something like Vector3.MoveTowards to push the transform in a direction per frame with a max amount it can move per frame

willow iron
#

fixed speed

shell sorrel
#

then you can add other concepts as needed like how long it takes to accelerate and deaccelerate

scarlet skiff
#

i want my player to be able to spawn in a random position (2d platformer side scroller).
whats the most optimal way to get a random position within a certain distance of the players death location that the player can safely spawn in (meaning head or toes wont be inside any objects with the layer ground).
if there is a tutorial that touches on this mechanic specifically, please let me know

willow iron
#

so the variable needs to remain a vector3, no quaternion conversion

shell sorrel
#

get the Quaternion.LookRotation of your directinal vector, then you can use Quaternion.RotateTowards feeding in the objects current rotation, and the LookRotation and a max degrees update

carmine ocean
#

i just wanna check is this the right channel to ask for help?

frail hawk
#

read the channel title

carmine ocean
#

ah sorry i dont really go in servers thank you tho

#

ive been struggling with finding the right resources and i dont know where i should really look for learning unity, could someone point me in the right direction?

frail hawk
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

carmine ocean
#

thank you for the guidance ill be sure to check all this out

frail hawk
#

they still haven´t fixed the learn pages for germany. it´s still down

daring tree
#

Hello guys, first time here!
Trying to instantiate a GameObject @ a certain time rate, but it keeps instantiating at every frame even after the timer resets
void Update()
{
Timer = Time.time;
if (Timer >= SpawnRate)
{
SpawnBalloon();
}

    MoveSpawn();
}

void SpawnBalloon()
{
    Timer = SpawnRate - SpawnRate;
    Instantiate(Balloon, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);
}
valid violet
#

add the line Timer = 0; after SpawnBalloon

#

and Timer+=Time.deltaTime

slender nymph
#

They're doing that inside SpawnBalloon, the issue is how they are tracking time though as just setting it to 0 won't work

valid violet
#

not Timer = Time.Time it is not correct

#
    {
        Timer += Time.deltaTime;
        if (Timer >= SpawnRate)
        {
            SpawnBalloon();
        }

        MoveSpawn();
    }

    void SpawnBalloon()
    {
        Timer = 0;
        Instantiate(Balloon, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);
    }```
eager scarab
#

im confused, how is void wrong in void FixedUpdate()

using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    public Rigidbody rb;
    public float moveSpeed;
    private Vector2 _moveDirection;
    public InputActionReference

    void FixedUpdate()
    {
        rb.linearVelocity = new Vector2(_moveDirection.x * moveSpeed, _moveDirection.y * moveSpeed);
    }
}```
modest dust
eager scarab
#

oh

#

doesnt say that

#

but its fixed now

daring tree
#

Thanks @valid violet , that solved it!

modest dust
#

It does

eager scarab
#

oh

#

yea it does just more complicated way of saying it

humble ridge
#

Hi guys! I was watching a tutorial of Unity Input System in Unity 6, and when they use MovePosition in rigidbody, they multiply it with Time.deltaTime, but the logic is implemented in FixedUpdate. Why not use Update instead? I guess cause it's physics related, but why use deltaTime then?

modest dust
# eager scarab doesnt say that

Member declaration, the member being public InputActionReference, followed by invalid void which shouldn't be there, that's why void is underlined

slender nymph
# eager scarab doesnt say that

because you didn't finish the previously line it thinks you are trying to finish it there but void is a reserved keyword so it is not valid in that previous line

humble ridge
frail hawk
#

deltatime and fixeddeltaTime is what i am saying

humble ridge
#

I've read that it can be cause the fixed updated rate could be modified over time, but a part from that, idk why they use it then

frail hawk
#

MovePosition as the name says is using the rb position, that is why you need to use it

humble ridge
#

Hmm okay, so I can use FixedUpdate for MovePosition without worrying about using deltatime or fixeddeltaTime ?

frail hawk
#

you have to use deltaTime, in short

humble ridge
#

And for reading the values of vector2 in Move action, it's okay to keep it in update or better to set it in fixed update too?

frail hawk
#

it is unclear what you are asking. do you have the code

humble ridge
#

Sure, I can send you the unity tutorial link too if you want

humble ridge
frail hawk
#

yeah looks ok from here

humble ridge
#

Sure, but sorry if I didn't make myself clear. Why do I need to use a Time variable (deltatime and fixeddeltaTime)?

#

I thought that fixedupdate was enough to not depend on framerates

night raptor
frail hawk
#

good questions actually, FixedUpdate runs 50 calls per second as we know, so why the deltatime

night raptor
#

You also generally want to work with some clearly defined units, like acceleration of m/s^2, you may not get any of that if the physics timestep (Time.fixedDeltatime) is not factored in correctly

humble ridge
night raptor
humble ridge
#

Thanks! Now I got it

night raptor
# humble ridge Thanks! Now I got it

Btw, in fixedUpdate, it doesn't really matter whether you use Time.deltaTime or Time.fixedDeltaTime, because deltaTime is identical to fixedDeltaTime during fixedUpdate. It is good practise to prefer fixedDeltaTime though to indicate that you are working with physics timesteps

humble ridge
#

Also, this m_moveAmt will be dependant on normal frame rate if called in update right? Or it has nothing to do with it

night raptor
# humble ridge Also, this m_moveAmt will be dependant on normal frame rate if called in update ...

Shouldn't have anything to do with it. AddForceAtPosition increments Rigidbody.GetAccumulatedForce (well not the getter of course) which then will get applied during the next physics update. AddForceAtPosition doesn't take Time.deltaTime into account in any way as far as I know, it just applies the given impulse (in the impulse ForceMode) to the counter (accumulatedForce). Don't know how much sense that makes to you. What is important though is that you do ForceMode.Impulse as you do, if you used something like ForceMode.Force, you would get different jump heights if you changed the physics time step (your regular framerate wouldn't matter still). ForceMode.Force expects you to apply that force continuously in every frame, Impulse you can apply only once.

humble ridge
#

Got it, thanks!

#

Really, that was a really good explanation, tysm!

night raptor
#

np

languid forum
#

guys can someone help me with some tutorials/pathways from learn.unity.com? some are good? i have a best/good knowledge in coding but not in unity, in c/c++ but i need to learn unity for a project. i did Unity Essentials and Junior Programmer and i want to start rn VR Development from learn.unity.com/pathways but i don t feel like i improved a lot, if someone know some tutorials/courses from learn.unity.com? in this ideea. i need to learn unity/VR

humble ridge
rich adder
vocal quiver
#

!code

eternal falconBOT
vocal quiver
#

guys take a look at this code snippet
https://paste.mod.gg/ntklmoluocoa/0

I have an object with x rotation -10 degrees and I want it to go to 40 degrees it does exactly that BUT for some reason the rotation the gets reversed and it comes back up. I dont want that to happen anyone know any solutions?

wintry quarry
#

you'd have to show more code

vocal quiver
wintry quarry
foggy crypt
#

Need help rotating an object while it is moving via Transform.Translate
Tried LookAt and RotateTowards and a couple of other methods but in the end the result was - that the model of the object was not rotating.
The only thing rotating were Vectors and directions of X and Z Coordinates

(What I'm trying to do is - create a projectile of a straight line and make it look directly at the player while flying)

wintry quarry
vocal quiver