#💻┃code-beginner

1 messages · Page 646 of 1

rain tartan
#

theres no index in a dictionary

naive pawn
#

foreach uses the iterator pattern, you can too

wintry quarry
#

There is no index

#

Dictionary is not ordered

quick pollen
#

though I think I found a method for it

dusty fern
#

the player sprite disappears

frail hawk
#

why do you have the camera follow on the playeR? this is causing the problem..

quick pollen
#

ProjectilePools[projectileInfos[i].name] this just looks a bit stupid

#

ProjectilePools is a Dictionary with a string key and an objectpool value

frail hawk
#

here is the line: transform.position = Vector3.Lerp(transform.position, PlayerController.Instance.transform.position + offset, followSpeed);

quick pollen
#

projectileInfos is a list of structs, where name is a string

rain tartan
#

You can check Linq syntax for dictionaries. I haven't used it much personally but my brother likes it

frail hawk
#

and please less ai generated code.

rain tartan
dusty fern
#

i was following a camera follow tutorial tho…

rain tartan
#

one bump in case anyone knows

frail hawk
#

wth are you doing, do you have an audiosource for each clip or what

#

all you need is a list of audioclips and one audiosource. you can use the PlayOneShot method

rain tartan
#

for example, if 10 bullets hit the wall im instantiating 10 hit prefabs, each with their own audio source and sound clip

#

is that terribly inefficient? or neglibable? or moderate

#

I can look at profiling it myself, just wondering if anyone knows off the top of their head

round sinew
#

Hello can anyone help with wheel colliders. The bike just wont stop dragging on the floor

mental burrow
#

weird jittering happens in the game display when moving. i tried so many solutions online but nothing worked. i tried enabling "Grid Snapping: Upscale Render Texture" in the pixel perfect component which worked but now its not smooth at all, any way to fix that? using cinemachine if that makes a difference

round sinew
frail hawk
#

well speaking of 32 audiosources and stuff i thought you might have never heard of it.

rain tartan
#

Yea thx. Ok cool, im thinking something up. Ill post back if I measure the performance costs I guess. Will probably not instantiate a bunch of audio sources on demand because that feels so wrong lol

frail hawk
#

i feel the same tbh

round sinew
#

can anyone help me with the problem?

quick pollen
#

Sooooo appareantly ObjectPool.Get() completely ignores already existing objects in its pool and always tries to create new ones?

#

I have a function which creates X amount of objects for the ObjectPool, that way I don't need to do it in the middle of the game, rather in a loading screen

#

but for some reason, even if there are objects already made this way, the objectpool just decides to make new ones instead of reusing old ones?

runic lance
quick pollen
#

because ObjectPool.Dispose() is the one that's meant to completely destroy the object, instead of returning it

#

I basically do 2 loops inside awake
one of them calls Get 100 times, and the other one calls Release 100 times

runic lance
#

that looks right, you should show us the !code then

#

oh no where is the bot

quick pollen
#

!code

eternal falconBOT
quick pollen
#

there it is

#

yea gimme a second, I'll try one more thing

#

I tried logging CountInactive and it says its 0

#

same for CountAll

#

even tho the objects clearly exist in the scene

round sinew
#

Hello! Im making a bike game and i have aproblem when i want to drive the bike it just starts glitching and driving on its own.
Here is the footage and i can also send script and settings:

quick pollen
#

yea we'd need a script

#

tho it looks like a store one or something

#

just based off of the inspector

round sinew
quick pollen
eternal falconBOT
round sinew
#

!code

eternal falconBOT
quick pollen
#

as in

#

use one of the paste links

#

like pastebin or hastebin or smth

#

huh....

round sinew
#

thats not it

#

wait

quick pollen
#

yea I doubt you made that in HTML lol

round sinew
#

yeah i clicked ctrl+s

#

finally

#

Are you here?

quick pollen
#

where did you get this script from?

#

also, if I had to guess, the problem is probably with the parameters inside the inspector, not the code itself

round sinew
#

Chatgpt😅

#

Half of it

#

I started with a youtube tutorial

#

Everything worked, but then i had to stabilise it and asked chat gpt for help

quick pollen
#

I'll be real with you, I'm not even going to try to help with AI generated code, I'm sorry

round sinew
#

its alright, im just starting out and helping myself with AI and stuff

#

i know it might not be the best learning process but im getting there

quick pollen
#

well, I'd say it's okay if you use it for like basic C# syntax stuff

#

like, idk, explaining dictionaries or some concept and give examples

#

but 90% of the time you are better off learning how to use the documentation

#

you have all the info there anyway

#

its a bit hard to sort through documentation info when you are starting out, it might feel like a lot

round sinew
#

yeah its my dream to make a game and i just want to start with AI, because im already learning

quick pollen
#

but as you progress, you will start to get familiar with the terms, and learn what you need to focus on when searching

unkempt flicker
#

Using AI is a great tool for learning, but AI has a tendency to use "whatever fits" style of code (not in all cases). You'd be better of using AI more as a reference, inspiration, or debugging for things you might've missed, asking questions like "What are some good methods to make an object move" etc.
Then you can do your own research on the subject and pick what best fits your need

quick pollen
round sinew
#

yeah youre right

#

nothing even worked

quick pollen
#

its good to point you in directions for what to use (sometimes), but not great otherwise imo

#

one time I tried using chatgpt too

round sinew
#

but i got the simple things to understand like colliders and such

quick pollen
#

I got put on a wild goose chase for a function that didnt even fucking exist

#

it just came up with it from who knows where

wintry quarry
naive pawn
quick pollen
#

if you know how to sort through the bullshit

#

because it can say bullshit, and it can say it confidently

naive pawn
round sinew
#

thank you for the help

naive pawn
#

(and imo you aren't really learning at that point, because you have to already know the bullshit)

quick pollen
#

@round sinew actually, what kind of bike controller are you looking for, anyway?

#

do you need one which is very realistic, or no?

round sinew
quick pollen
#

because you can make some really basic movement without needing wheel colliders anyway

round sinew
#

because its a bike based game

quick pollen
#

do you have a basic understanding of physics?

#

as in, what torque and such is?

round sinew
#

kind of yeah

quick pollen
#

then I would suggest looking up some tutorials on how to do it, while also looking at the documentation mainly to try to see what you can use

round sinew
#

i searched for tutorials on youtube and there are none that actually fit what i need, most of them are just promotions for their assets

#

So i started looking at car tutorials but the problem is they dont show how to stabilise it

quick pollen
#

maybe I'd learn by making a single wheel move first?

round sinew
#

you mean by only adding a wheel?

quick pollen
#

yeah

#

to try to understand how moving it works

#

then you can add a second one, which basically makes a bike already

round sinew
#

thats a good idea

#

i will also look at the tutorials at the same time and i will slowly start to understand

#

you guys actually helped a lot

quick pollen
#

personally I hate tutorials, like youtube videos

#

I started on them as well

round sinew
#

yeah they are mostly just copying the code and thats it

quick pollen
#

but they just "mouthfeed" the code to you yeah

#

idk what the term is, my bad

#

its also really hard to make a good tutorial

#

and most people only do it for the revenue

quick pollen
#

so yeah, if you want to get into coding, you better get reading

#

taking notes even, if you want

round sinew
#

did you learn code by yourslef or in school?

quick pollen
#

by myself

#

though I'm no expert in any way

round sinew
#

youtube or google or what?

quick pollen
#

mostly the Unity docs

#

and also a lot of asking here

#

appareantly I have over 16k messages here lmao

round sinew
round sinew
quick pollen
#

good luck, still! look some things up, and if they get too unclear, then come here and ask

round sinew
#

yeah thank you, i hope i will once finish my project

unkempt flicker
#

Start small! 🙂 Unity's learning curve only gets higher. Start with finishing simple games before moving to tackle bigger ones. It will save you mentally (and also computer memory-wise 😆)

round sinew
#

thanks

acoustic belfry
#

Hey, how i can make that if 4 objects get destroyed, another object function is activated?

i mean cuz i have a 2D shooter plataformer and i want that when i kill X amount of enemies in a room, a door opens

quick pollen
#

you can also make it so the enemies call a function on a different script when they die (like on the script of the door) which decreases some counter, and once that counter reaches 0, the door opens

acoustic belfry
#

oh, makes sense

thanks a lot :3

but also, i been struggling to make a dialogue system

i know how to make a canvas empty object that dissapears and appears when i want to, and display different texts and images, but the issue is...

How i can keept it as a sequence? like,
it displays first dialogue, then second dialogue, then third, and that

quick pollen
#

you could use a list

acoustic belfry
#

a list?

quick pollen
#

like you create a list of dialogues beforehand

#

and then you just go through them in order

acoustic belfry
#

how?

quick pollen
#

something like what Undertale did (just don't do it the way Toby did it holy fuck)

quick pollen
acoustic belfry
#

i dont know how that script should go

quick pollen
#

but you could have a list of strings

acoustic belfry
quick pollen
#

TMO?

#

you could also make it a struct

acoustic belfry
#

my bad

#

TMPro

quick pollen
#

ohh

#

well, you could have a list of strings and images

#

or just a list of structs which has string and and image

night mural
# acoustic belfry i dont know how that script should go

If you have a list or array of 'dialogue's, you can keep track of which index is the current one (0, 1, 2, etc) and display that one. Then to display the next one, you add 1 to the index and display the new correct dialogue

quick pollen
#

and you could just go in the inspector, type in the texts, set the images, and that sit

acoustic belfry
#

;-;

night mural
quick pollen
#

you can declare a struct

struct Dialogue{
    string text;
    Image image;
}

and then do

[SerializeField] List<Dialogue> dialogues;```
#

this isnt exactly correct

#

so you should look up these terms

naive pawn
#

it's almost correct

quick pollen
runic lance
# quick pollen there it is

so, I did some testing here and it's pretty strange 🤔
for some reason the pool doesn't work as expected in the first one or two frames of the application, it just creates the objects and then forgets about them
this behavior is not documented anywhere, so I would guess that this is a shiny Unity bug

naive pawn
quick pollen
#

I swear, objectpools are so buggy for no reason

#

I made one before and it was literally less buggy

naive pawn
#

(though the Image could probably be something else, a Sprite or Texture2D i think? i don't remember which)

quick pollen
#

...and probably more inefficient, but whatever

acoustic belfry
#

i think image would do the trick

quick pollen
#

but yea I think its Sprite

night mural
#

the thing you populate will probably be an Image (in the UI) but the thing you populate it with will probably be a Texture2D

#

er Sprite, actually?

#

probably either could work

runic lance
#

Texture2D is for RawImage

acoustic belfry
#

holup, it would be a bad idea to make that everytime i press a keyboard, or a button doesnt matter, it makes a INT inside the dialogue script to go up, and that each text and each image is displayed when a number INT number is the specified?

night mural
acoustic belfry
#

thanks :3

quick pollen
#
                    Vector3 dir = transform.forward;
                    dir.z += pattern.initialAngle;
                    float step;
                    if(pattern._shotsCount <= 1)
                        step = 0;
                    else
                        step = (Math.Abs(pattern.initialAngle) + Math.Abs(pattern.finalAngle)) / (pattern._shotsCount - 1f);
                    Debug.Log(step);
                    for(int i = 0; i < pattern._shotsCount; i++){
                        ProjectileHandler.Instance.AddProjectile(proj.GetComponent<Projectile>(), dir);
                        dir.z += step;
                    }```
#

can someone tell me what I'm doing wrong with the direction calculations?
I am basically trying to create a shotgun effect, where an object shoots out (gonna use exemplary numbers) 5 projectiles in a 180 degree radius

#

so initialAngle is -90, finalAngle is 90, shotsCount is 5

#

problem is, I get 2 shots backwards, and 3 shots forwards

#

then I just do rb.linearVelocity = dir.normalized * speed;

quick pollen
#

yeah

naive pawn
#

or cone, i guess, for 3d

#

well... it wouldn't be much of a cone if it were 180°

quick pollen
#

think arcs for now for simplicity

#

i mean arcs, my bad

#

so basically

#

take the current forward direction

naive pawn
#

what's 180 here

quick pollen
#

rotate it pattern.initialAngle degrees

#

and then shoot, rotate by step, shoot again, etc, shotsCount times

naive pawn
#

wait uh is this supposed to be random spread (within the cone) or a fixed pattern?

quick pollen
#

fixed pattern

naive pawn
#

(i would expect the former for a shotgun)

#

ok cool

quick pollen
#

so you know

#

I shoot out 5 projectiles

#

each with a 45 degree angle between them

#

so I cover a total of 180 degrees

#

right now it doesnt work in any way

naive pawn
#

well i see you have a Debug.Log there, does step line up with what you want?

quick pollen
#

like it always shoots 2 backwards and 3 forwards, no matter the angles

quick pollen
naive pawn
#

what about the value of dir?

quick pollen
#

i think the problem has to be with the Vector3 dir = transform.forward; part somewhere

#

this seems correct

naive pawn
#

and where are you facing?

quick pollen
#

(here its -30 and 30, not -90 and 90)

quick pollen
naive pawn
#

i mean, what's transform.forward

quick pollen
#

seems to be just (0, 0, 1)

naive pawn
#

so that's correct right

quick pollen
#

seems to be

naive pawn
#

so there's no issue in the math then

quick pollen
#

well, i dont think i should be using transform.forward

naive pawn
#

....wait, changing z would be rolling

quick pollen
#

but im not sure

naive pawn
#

that should be fine

quick pollen
naive pawn
#

but you would have to rotate y instead, not z

#

but if that were the issue, all the bullets would be spawning at the same place

#

so i still think it's to do with the spawning

quick pollen
#

uhhh, almost??

#

hold on its close

#

i think it needs to be x

naive pawn
#

rotating x would make the vertical position change (pitch)

quick pollen
#

yeahh its x

naive pawn
#

also the z=1 on the rotation would mean that your shooty thing is slightly tilted

quick pollen
quick pollen
#

it seems to work now... almost...

naive pawn
quick pollen
naive pawn
#

is it parented to anything?

abstract finch
#

do 3d projects compile slower than 2d because of asset sizes in unity?

quick pollen
#

tbf its a normalized vector

quick pollen
naive pawn
#

oh yeah

#

im dumb, i was thinking it was transform.rotation

#

i need sleep...

quick pollen
#

hold on

#

wtf

naive pawn
quick pollen
#

                    Vector3 dir = transform.rotation.eulerAngles;
                    dir.x += pattern.initialAngle;
                    float step;
                    if(pattern._shotsCount <= 1)
                        step = 0;
                    else
                        step = (Math.Abs(pattern.initialAngle) + Math.Abs(pattern.finalAngle)) / (pattern._shotsCount - 1f);
                    for(int i = 0; i < pattern._shotsCount; i++){

                        GameObject proj = ProjectileObjectPools.Instance.GetProjectile(pattern.projectileName);
                        ProjectileHandler.Instance.AddProjectile(proj.GetComponent<Projectile>(), dir);
                        dir.z += step;
                    }```
#

this seems to work

#

but its weird that it does

#

I change dir.x in the beginning

naive pawn
#

@quick pollen im starting to think you can't modify transform.forward like that
it wouldn't be an arc, you'd have to do trig yourself
but you could modify the rotation instead

quick pollen
#

and then change dir.z when rotating

quick pollen
#

they make more sense in this case

naive pawn
#

yeah that's what i mean (and what i thought it was before lol)

quick pollen
#

welp

#

it works to some extent

#

i just cant get the initial offset right yet

#

which is why I'm guessing dir.x is incorrect

#

yea my brain hurts

#

i hate doing maths like this

#

i think it has to do with the fact that my direction is normalized

#

yeah its really problematic that it gets normalized

#

but if i dont normalize it, then it goes haywire

#

im doing maths very wrong

naive pawn
#

don't use the direction, just use the rotation

quick pollen
#

i think ill just stick to rotating them

#

yeah

naive pawn
#

if you use directions you have to do trig to make it an arc

quick pollen
#

I just made a system where I can use animationcurves for changing the velocity

#

and i thought itd be cool to use that

#

figured it out!

#

yeah, rotations will make sure its easier

#

thanks for the help still @naive pawn !

#

my angle math wasn't wrong, only my rotation maths (a.k.a. the most important part)😅

fading barn
#

Do we need to multiply force being applied to a rigidbody with Time.deltatime if the movement function is being called in fixed update

slender nymph
#

no, you shouldn't be multiplying your forces by deltaTime

fading barn
#

my rigidbody is haulted

#

also if i have a character prefab with armature and mesh as its children

#

to which gameobject should i assign rigidbody and collider and movement script\

slender nymph
#

the rigidbody should be at the root of the moving object. colliders that are attached to that same object or are children of that object (but not attached to another rigidbody or its children) become part of that rigidbody's compound collider. your component for controlling the rigidbody should just be where it makes most sense to have it, though typically people put it on the same object as the rigidbody component

fading barn
#

how do i write code in discord

slender nymph
#

!code

eternal falconBOT
fading barn
#
if(PlayerRigidbody != null)
{
    if (!IsJumping)
    {
        PlayerRigidbody.AddForce(WalkForce * Vector3.right * Input.GetAxis(InputAxis.Horizontal));

        if (PlayerRigidbody.angularVelocity.x != 0f)
            animator.Play(anim.WALK);

        else
            animator.Play(anim.IDLE);

    }

#
    private void ControlPlayer()
    {
        //Move
        if(PlayerRigidbody != null)
        {
            if (!IsJumping)
            {
                PlayerRigidbody.AddForce(WalkForce * Vector3.right * Input.GetAxis(InputAxis.Horizontal));

                if (PlayerRigidbody.angularVelocity.x != 0f)
                    animator.Play(anim.WALK);

                else
                    animator.Play(anim.IDLE);

            }

            //Jump
            if (Input.GetKeyDown(JumpKey))
            {
                PlayerRigidbody.AddForce(JumpForce * Vector3.up, ForceMode.Impulse);
                IsJumping = true;
                return;
            }
            if(PlayerRigidbody.angularVelocity.y == 0f)
            {
                IsJumping= false;
            }
        }
        
    }
#

this is not working as expected

slender nymph
#

"not working as expected" is not descriptive. what specifically are you expecting to happen that isn't happening

fading barn
#

movement is slow animations are not platying

slender nymph
#

also large blocks of code should be a link, and when inlining code you should really include the language so there is syntax highlighting

slender nymph
fading barn
#

i tried debugging

#

but was unable to find any solution

slender nymph
#

and what debugging have you done

fading barn
#

i tried setting a breakpoint in areas where the code was not working like movement and animations setters and to my surprise the code of that was executed but didnt work in game

#

i dont know much about debugging

slender nymph
#

Have you done anything to make sure that the values you are using are what you expect them to be?

fading barn
#

yeah man its in the inspector i tried to fiddle with them too

#

i am thinking of deleting script and rewriting the code

#

cause i cant find the problem

slender nymph
#

Try actually logging all of the info when it is being used

#

Also consider why you are using the rotational velocity to play your walk animation

stuck palm
#

I'm generating little timeline frames like this, where I'm setting an internal value to the index of the for loop. the numbers on top of the button are from the index constructor, so the values should be correct. However, when I press, it always tries to access the count of list, so in this case 28. Very confused here, anyone know what could be happening here? is using a lambda like that bad?

for (var index = 0; index < activeMove.FrameData.Count; index++)
        {
            var datum = activeMove.FrameData[index];
            TimelineFrame frame = new TimelineFrame(index, () =>
            {
                Debug.Log("Setting to move " + index);
                CurrentFrame = index;
                UpdateActiveFrame();
            },datum.Hitbox.ShapeType != Shape2DType.None, datum.Hurtbox.ShapeType != Shape2DType.None);
            
            FrameList.Add(frame);
            TimelineElement.Add(frame);
        }
fading barn
slender nymph
#

why not check the docs to see what each one is and make an informed decision

fading barn
#

cause its boring 🥲

#

i like videos or chatting

fading barn
#

but i will read it

stuck palm
#

thats interesting, thank you

#

yeah thats done it

#

strange how that happens

slender nymph
polar dust
# fading barn cause its boring 🥲

whilst that is true, think on the other hand, about how boring all the time of "when stuck ask discord for help, wait some time for a response, fix the problem" that will add up as time goes along

#

its no problem, as in the beginning, you are a beginner after all

#

but if you can get a head start sooner rather than later, youll be saving yourself a lot of time down the road

scenic saffron
#

how would I get the in world mouse position in a 2D scene?

slender nymph
#

Camera.ScreenToWorldPoint

scenic saffron
#

thx

slender nymph
#

also google it next time

quick pollen
#
            float angle = CurveEvaluation(ActiveProjectiles[i].rotationCurve, ActiveProjectiles[i].rotationSpeed, lifetimes[i],                           ActiveProjectiles[i].lifetime);
            Vector3 rotation = Quaternion.AngleAxis(angle, Vector3.up) * ActiveProjectiles[i].transform.forward;
            ActiveProjectiles[i].transform.rotation *= Quaternion.Euler(rotation);
            rb.linearVelocity = velocities[i];
            velocities[i] = ActiveProjectiles[i].transform.forward * CurveEvaluation(ActiveProjectiles[i].speedCurve,                                     ActiveProjectiles[i].moveSpeed, lifetimes[i], ActiveProjectiles[i].lifetime);```
#

anyone know which part I'm fucking up with the rotation here?

#

I want to make it so the projectiles slowly rotate over time

#

but I just can't figure out the quaternion maths to do it

#

this is what they would look like normally, without any rotation

#
rb.linearVelocity = velocities[i];
            velocities[i] = velocities[i].normalized * CurveEvaluation(ActiveProjectiles[i].speedCurve, ActiveProjectiles[i].moveSpeed, lifetimes[i], ActiveProjectiles[i].lifetime);```
#

the CurveEvaluation function only returns a float, its not really important, that part works

eternal falconBOT
#
Visual Studio guide

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

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

jaunty bone
#

ty

quick pollen
#

appareantly none of the functions that "turn a direction into a quaternion rotation" do what I think they do

#

by that I mean LookRotation mainly

wraith shuttle
#

why my script isnt working , i want when the enemy hit an object called player(basically the player ) it quits the game

quick pollen
#

it only works in build mode

wraith shuttle
quick pollen
#

also CompareTag doesnt check the name of an object, it checks the tag

wraith shuttle
#

Thanks ❤️

wraith shuttle
#

i have a tag called player

quick pollen
#

you're welcome

shell sorrel
#

for editor you can just have it log or add a ifdef so it changes play mode state

wraith shuttle
#

and with collison is trigger and rigidbody

hasty adder
#

anyone know how to make teleportable portals? ive tried very hard but i cant find any FREE WORKING assets, by working i mean you can teleport objects or yourself because id rather not have an effect :D

slender nymph
#

with a basic implementation it would just be trigger(s) and assigning the position

hasty adder
#

yeah but does anyone have a guide

eager spindle
hasty adder
#

just to be clear

#

does this work with VR

eager spindle
#

used this before it's goated

#

I'm outside rn so can't create one 😦

hasty adder
#

i hope this works

hasty adder
#

didnt work?

#

the display is white and it doesnt tp

teal viper
hasty adder
#

ok i got it to work but

#

if i add the portal renderer

#

the camera doesnt move

#

its vr btw

teal viper
#

Might need to get it working in the pc first.
Then research how it works and adjust for VR. Might be quite difficult.

novel nymph
unkempt flicker
novel nymph
#

Ill do that

hasty adder
#

ok now the player falls through the ground?

novel nymph
elfin isle
#

hey hey people :D i have a little equation of a fish jumping in and out of water, though whats weird is depending on who runs the game the speed of the fish changes. i personally assume its because i use "time.deltatime" though when i dont use it they almost lag a little bit. how should i fix this? (from knowing my friends specs, the worse the computer the slower the fish) heres the code of the fish i have;

            {
                    Destroy(Fish);
            }
            if(Fish.GetComponent<Fish>().isAlive == true)
            {
                    num += Time.fixedDeltaTime;
                    y = iy + (2.5f * Mathf.Cos(num  * 0.4f));
                    Fish.transform.position = new  Vector3(Fish.transform.position.x + 0.02f, y + 0.5f, Fish.transform.position.z);
            } else {
                Fish.transform.position = new Vector3(Fish.transform.position.x + 0.005f, 0.73f, Fish.transform.position.z);
                Fish.transform.rotation = new Quaternion(90f, Fish.transform.rotation.y, Fish.transform.rotation.z, 0f);
                Fish.GetComponent<Outline>().OutlineColor = Color.white;
            }```
unkempt flicker
# elfin isle hey hey people :D i have a little equation of a fish jumping in and out of wate...

Using Time.deltaTime actually normalizes out timing on things based on framerate vs. when you don't use it, your timing varies depending on computer specs (how many frames per second are actually calculated / displayed).

Using Time.fixedDeltaTime is used mainly for Physics as it uses a set time of exact timeframes, rather than relying on the computer's framerate. Which could potentially be causing that stutter effect.

If you're block of code is wrapped inside a FixedUpdate() in theory it should be fine, otherwise you may want to consider switching to Time.deltaTime.

A little more context may help solve your issue, with what's provided it's rather hard to determine what your intended goal is 🙂

elfin isle
solid heart
#

!vs

eternal falconBOT
#
Visual Studio guide

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

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

wet pivot
#

Is it possible to output the return of a function to the inspector?

#

For example, public bool BoolFunction() { // some code here}

slender nymph
#

probably with a custom inspector for the type or if you want a really dirty solution you could call it in OnValidate and assign it to a serialized variable
but is there a reason you need to do this?

wet pivot
#

Just debugging purposes. I have a function that checks if the player is on a slope and outputs a bool and I suspect it may be causing issues with other parts of the code.

slender nymph
#

why not just log it instead?

#

using the inspector you won't see things like the value being different for only one frame

wet pivot
#

dang true

#

ok i can confirm the slope checking was not the issue. I'm gonna keep looking into this

rich adder
#

eg
var color = IsOnSlope() ? Color.green : Color.red Gizmos.Color = color Gizmos.DrawRay(pos, vector3.down)

unkempt flicker
#

You technically could return the value from a bool function but you would need a global variable to store it, and some modification to your block and in most cases you aren't trying to output it strictly to the inspector, so it's pretty overkill in this case where a debug does more than enough 😛

shut swallow
#

https://paste.mod.gg/wsfywjzjiylc/0 why does my character not rotate with my camera and why couldn't I move even if I have a valid _requestedMovement? (Reference: https://www.youtube.com/watch?v=NsSk58un8E0 timestamp 6:45)

This one is a bit different than the last couple devlogs. I thought it would be fun to share a longer video where I actually make a thing. Might be super boring? Idk!

Links:
https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
https://youtu.be/7daTGyVZ60I
https://youtu.be/tYc1yUt0IeA
https://github.com/TheAllenChou...

▶ Play video
#

I tested that I do have a valid requested movement that rotates with my camera (even if it's currently not clamped properly because it's not horizontal) but in theory it should be able to move my character

slender nymph
#

stop throwing exceptions in all of the unused methods, just don't do anything in them (or return default values for ones that require a return), when an exception is thrown the executing method must either catch it or it will be stopped as well so you are basically just preventing the methods from being called because you throw an exception in the earlier update methods

shut swallow
#

oh that comes by default when i use the kinematic motor addon

#

but good point

slender nymph
#

it's not the asset that added it, it's your IDE adding it when implementing the interface methods automatically

shut swallow
#

ah

#

i doubt deleting these will fix my code tho lmfao

hazy cliff
#

so I am copying my respawn mechanic over from one project to another and I have triple checked everything is exact but for some reason the code doesn't work even though it's exactly the same. I have logs that are detecting the collisions and to activate the code but for whatever reason the code to teleport the player just doesn't work does anyone know a reason for this?
Here is the line of code that should work but doesn't:
transform.position = new Vector3(0.0f, 1.7f, 0.0f);

slender nymph
#

are you using a charactercontroller?

hazy cliff
#

yes

slender nymph
shut swallow
slender nymph
#

and you have confirmed there are no exceptions in the console now?

shut swallow
#

on the IsColliderValidForCollisions I still throw the exception because if i don't it returns an error "not all code paths returns a value" and cannot compile

hidden fossil
#

i have a question is there a difference between rb.velocity and rb.linearvelocity?

slender nymph
slender nymph
hidden fossil
#

oh so i can just change all my rb.velocity to rb.linearvelocity so it can stop sending me warning messages?

slender nymph
#

assuming the warnings are about how the property is deprecated, yes

shut swallow
#

ran into that a while ago lol

#

wait my code works

#

after i passed the default value in

slender nymph
#

like i said, the exceptions were preventing the code from running

shut swallow
#

ahhhh

#

thanks a lot

#

can't believe it was that simple

coral crater
#

on update, my NPC moves towards its current destination. the destination is randomly rolled, so it can move in any theoretical direction on the top-down plain, it moves 360 basically.

I'm trying to implement a small circle that's in front of the player, it's job is to detect when the NPC is about to bump into something, so I need it to always be in front of the NPC in whatever direction the NPC is moving. I can't quite figure out the formula for this though. I've tried doing different things with the direction vector 3 and the NPC's current transform, but I can't quite get the formula right

formal valley
#

hii
how can I make my character stop stick to the wall

naive pawn
naive pawn
#

create a new physicmaterial2d
set its friction to 0
assign it to the wall or player

#

but keep in mind this would also affect friction on top of the platforms, so make sure to tune your linear drag as well

coral crater
keen dew
#

Why does the position need to be animated with code? Just put it in the correct place as a child of the player object

coral crater
keen dew
coral crater
coral crater
#

I basically just need it to be a hell of a lot less jittery, but don't rly know the formula c:

keen dew
#

The formula is checkInFront.transform.position = transform.position + (destination - transform.position).normalized * distance

coral crater
#

thank you so much blingee

rancid tinsel
#

Am I correct in thinking that the colliders on the child objects act like one big collider if I do OnCollisionEnter on the "Room" object?

sour fulcrum
#

you are incorrect afaik

hidden marten
#

//Move Player
Vector3 moveVector =
transform.TransformDirection(keyboardInput) * speed;
rb.linearVelocity = new Vector3(moveVector.x, rb.linearVelocity.y, moveVector.z);

this is my script for moving the player... since i am directly setting the velocity i am not able to add flat forces (in the x and z direction). is there a workaround for this? i dont want to use rb.addforce as i wound have to use counterforce or drag to stop the player.. both of which are complications i would not prefer to make

agile hearth
#

idk how to code

sour fulcrum
#

ok

agile hearth
#

but iam going to steal this code

#

because iam a theif

eternal falconBOT
#

:teacher: Unity Learn ↗

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

twin pivot
#

Oh wait replied to wrong person

#

Sorry

agile hearth
#

oh thanks

forest fractal
#

I'm trying to make a spawner for my roguelike game where enemies will only spawn until a cap is reached (MaxEnemies). How do I only use InvokeRepeating if certain conditions are met?

night mural
#

you can check in the function being invoked and return early based on your condition

#

really though, InvokeRepeating is dumb for exactly this reason and it usually makes more sense to have a timer which you can manage yoursefl

wintry quarry
forest fractal
#

ok, should should I spawn on update, and every spawn inteval check the conditions for spawning?

wintry quarry
#

With a coroutine you could do it like this:

IEnumerator SpawnEnemies() {
  while (true) {
    if (enemyCount < MaxEnemies) {
      SpawnAnEnemy();
    }

    yield return new WaitForSeconds(interval);
  }
}```
naive pawn
#

or perhaps throw a WaitUntil(() => enemyCount < MaxEnemies) in there

forest fractal
#

there's an issue with the code where the enemies spawn once and do not spawn again. I've called the IEnumerator function in Start

#

do I need to put it in an InvokeRepeating or leave it as is?

night mural
#

you need to put it in a StartCoroutine, did you do that?

forest fractal
hidden marten
eager elm
hidden marten
hidden marten
flat stump
#

I'm making some UI in unity and im trying to put in my game but im struggling with the offsets if i wanted something to go vertical multiple times how would I do it?

eager elm
#
Vector3 jumpVector;

void Jump()
{
    jumpVector = new Vector3(0, 5, 0);
}
void FixedUpdate()
{  
    rb.linearVelocity = moveVector + jumpVector;
    //Reducing the jumpVector over time
    jumpVector -= jumpVector * 0.2f * Time.deltaTime;
}
``` @hidden marten
silent valley
hidden marten
flat stump
silent valley
earnest wind
#
[Space] [Header("Toggles, Main")] [SerializeField] Toggle FullScreen, Vsync, Occlusion, HDR, FPS, PING;
    [Space] [Header("Toggles, Main - Ext")] [SerializeField] Toggle MinMaxFPSAndPing, AutoColorFpsAndPing;

Normally this would apply to everything, how can i make it be only 1 Header and not 1 header and space for each variable?

#

something like this

polar acorn
#

Header applies to the variable that follows it. You've put like a dozen variables following it, so it applies to all of them

earnest wind
polar acorn
#

If you don't put it before a field, it would be an error

polar acorn
#

If you put it before like a dozen fields, it's going to apply to all of them

polar acorn
#

Put it before the one you want it before

flat stump
earnest wind
#

ah so just get one of the variables out?

naive pawn
#
[Attribute] Field a;
```-> applied to `a`
```cs
[Attribute] Field a;
Field b;
```-> applied to `a`
```cs
[Attribute] Field a, b;
```-> applied to `a`, `b`
#

so if Attribute is a Header, you get a header above each field it's applied to

earnest wind
#

thanks

silent valley
# flat stump Just doing it custom via code with UI offsets

I'm not too sure as I've never had an issue with the component itself. But I'd assume you'll make an array for the rectTransform for your UI elements and then a float for the spacing you want. Grab the number of elements that are in the array, determine the position that the UI is in then set a new vector2 with the original position plus the vertical offset float * the array int 🙅

round moon
#

does anyone know how to solve this error ?

round moon
naive pawn
#

please do not for the love of god take pictures of screens

round moon
#

i cant ss coding from udemy web bro thats why i take picture from my phone CryCat srybro

fading barn
#

how do i make a 2d object orbit around another 2d object in unity

polar acorn
high wagon
#

Hi, I’m a new game developer to unity, and don't understand C# very well. I'm using cinemachine to make cutscenes, and I have two timelines for two cutscenes. One for zooming in on a laptop, and one that will only activate when pressing a button on the laptop screen, which would move the camera. How do I switch the Playable Director between the two timelines? Any help appreciated!

rich adder
sterile radish
green copper
#

is there a way to give variables aliases?

for readability, I'd like to be able to tag something with a variable designating it as incoming or outgoing

i could just do incoming = true/false

but I'd prefer to do direction = incoming/outgoing

I could technically do it with enums but then it'd be

direction = direction.incoming and that's less readable

sterile radish
tribal edge
#

Ensure that Count isn't zero, I see you removing entries from the list

polar acorn
sand field
#

A little lost on how Instantiate works, I declared a GameObject to use but I think I am misunderstanding how I am supposed to tell it to spawn a specific prefab

private GameObject ballObject;
//code code code
Instantiate(ballObject , ballPos, ballObject.transform.rotation);
polar acorn
sterile radish
polar acorn
tribal edge
polar acorn
#

But your error indicates there is at least one enemiesToSpawn list that has nothing in it

narrow dust
#

Does making this asset's mesh collider convex, mean that nothing can go thru that invisible wall?

#

(sorry if wrong channel)

verbal dome
rich adder
polar acorn
sand field
polar acorn
sand field
#

oh

#

I see the issue

verbal dome
sand field
#

Yeah I get it now, thanks all

verbal dome
#

So add [SerializeField] attribute to ballObject to expose it in the inspector

#

Yea

sand field
#

Incredible that I find can get help here unlike the Blender discord lol

grand snow
#

programming questions often have a fixed answer which is useful

sterile radish
polar acorn
tribal edge
#

Again, you are removing items from the list. Its count is hitting zero

sterile radish
#

yes i am removing items from enemiesToSpawn purposefully after each enemy spawns but it should not interfere with the spawnCooldown calculations which is why im a bit confused

tribal edge
#

It does though, because you've made those calculations reliant on the count not being zero

polar acorn
sterile radish
#

yes but before i calculate spawnCooldown i call GenerateEnemies() which populates the enemiesToSpawn List so it shouldn't be empty

polar acorn
#

So, check to see if that's actually happening

sterile radish
#

okay, i've debugged each enemy gameobject in enemieToSpawn after it gets populated

polar acorn
#

Where is that getting logged

tribal edge
#

Try logging the enemiesToSpawn.Count before the division by zero error

sterile radish
polar acorn
#

So, at the time this runs, there are things in the list. Notably, however, this will print nothing at all if the list is empty

#

Thus making it kind of difficult to determine that the list is empty

sterile radish
tribal edge
#

Yep. You're all caught up now. You have a logic error. The code isn't doing what you think it is

#

I suggest taking a break for an hour or so and looking through it step by step

polar acorn
#

So your code is, at some point, not putting anything in the list

grand snow
sterile radish
#

okay, thank you all for the help i think JonBrant is right because this script was actually working fine i just wanted to transfer it to another one which is when it broke I think i'll probably rewrite the whole thing later. sorry to waste your time but thank you for the help!

round sinew
#

Hello, does anybody know how can i edit a prefab position and rotation:

grand snow
round sinew
grand snow
#

also not a code question

grand snow
round sinew
sand field
#

This just suddenly started happening

polar acorn
#

If you need both, you have to tell the code which Debug you want

sand field
#

It definitely added that on its own but thanks

slender nymph
#

you gotta pay more attention to what you are autocompleting then

polar acorn
hasty adder
#

using GoThrough on unity 2022, i need to get it in vr using the samples, i add the vr cameras then when i test it????? I FALL THROUGH THE FLOOR???

gleaming sluice
#

how do I use the Rider Debugger with Unity projects? the buttons are grayed out even when my Unity editor is running

keen cargo
eternal falconBOT
gleaming sluice
sand field
#
void SpawnBall()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Instantiate(ballObject, transform.position, Quaternion.Euler(0, transform.rotation.y, 0));
        Debug.Log(ballAngle);
    }
}

transform.rotation.y isn't producing what I thought, its always a value between -1, 1. Is there a better way to call the specific angle of the current object?

rich adder
grand snow
#

code channel
posts non code question 🤔

you should check the collider size and if its a tile map collider, check the extrusion factor.

true owl
#

thx

#

sry abt that

sand field
#

The goal btw is to have a ball launch towards whatever direction this object is facing, so if there's an easier way to do this I'd love to know

teal viper
#
  1. Get the transform rotation in Euler angles.
  2. Set the x and z to 0.
  3. Create a new quaternion from the new Euler angles.
  4. Pass it to instantiate
hushed ridge
#

how do i edit code like he does in the beginning of this video? https://www.youtube.com/watch?v=qQLvcS9FxnY

Very fast tutorial to make an FPS character in Unity in less than a minute!

PasteBin link for code: https://pastebin.com/RXZ1dXgw
GitHub link: https://github.com/dustinmorman/FPSControllerTutorial

Link to my Upcoming Game - Survive the Uprising: https://store.steampowered.com/app/1984690/Survive_the_Uprising/

Link to the Discord - https://dis...

▶ Play video
#

i see it's c# do i need to download vs for that

timber tide
#

You can use any IDE you want but vs has some plugins that'll help notify you of syntax errors and unity methods so you'd want it as a starting point

#

vs code is also another option

hushed ridge
#

can i write it in unity?

wraith shuttle
#

i want the bullets go forward they like stay

timber tide
wraith shuttle
#

like linearvelocity doesnt work

hushed ridge
#

for someone whose only experience is like

#

scratch

#

and microbit

#

should i get vs?

wraith shuttle
#

they stay like that

timber tide
wraith shuttle
solemn glacier
#

does anyone know how to stop the Player camera from clipping and seeing through walls "im in first person"

wraith shuttle
#

and u can download ipe or smth like that there which will help alot trust ,u can do it in vs code too btw

timber tide
#

near clipping rather

solemn glacier
#

@timber tide thanks this helped

sand field
#

Done for tonight, having a lot of fun, thanks for the help so far

wet pivot
#

Can I ask cinemachine related scripting questions in here or should I stick to #🎥┃cinemachine ?

solemn glacier
#

if i wanted to make a game multi player how early would u suggest i implement it

tribal edge
#

Immediately

solemn glacier
#

@tribal edge thx imma do that lmao

wet pivot
#

Eh, I'll ask anyway and feel free to tell me to go away lol

keen owl
wet pivot
#

How can I get the current live camera in code? I have a few I am switching between and want to change the FOV of whichever one is currently active.

fickle cosmos
#

I am making a timer in my 2d unity game. I have the script set up correct, and its supposidly updating the timer correctly (outputting to console). I have made a gameManager object running the script, and it is linked to the timer text. It shows up when the game is running, and is underneath my camera in the heirachy, As soon as I run the game, it disappears? apologise for the terrible techincal jargon, I am very new to unity!

keen owl
# fickle cosmos

We need to see an example of it disappearing. Why don’t you have your player referenced in your Game Timer script?

fickle cosmos
fickle cosmos
keen owl
fickle cosmos
#

you legend!!! thank you so much!

rich adder
oblique phoenix
#

Alright thanks.

fickle cosmos
#

Here is a 2d side scroller I am making in unity. The player can pick up this item, but only if is-trigger is turned on. the issue I am having, is that the item does not move to the bottom of the map (they spawn in above the terrain and are suppose to then drop down). If i turn off kinematic mode so it drops to the bottom of the map, it just falls through the floor because is-trigger is on. So I am unsure of what to do. Any help would be greatly appreciated

#

the battery is also a prefab i dropped in just for testing

unkempt flicker
rich adder
twin pivot
#

quick question, is this a good way of making the camera track the player?

timber tide
#

Usually you move the camera in late update

twin pivot
#

i see

#

thank you

timber tide
#

regardless you've some questionable stuff in that code

frosty hound
#

The best way would be to use Cinemachine and let that follow the player.

twin pivot
#

first time making a game with a player so i decided to just test out a few things

cursive rivet
#

I have a question:
when I move the house around and why sometimes it is behind the grid and not
is it related to Sorting layer and Order in layer?

fading barn
#

what is the input axis string for scroll wheel?

#

Input.GetAxis() ?

hushed ridge
#

what do i do if i went into a material and erased everything in vscode and then saved it and now everything is untextured

#

and i cant reimport

fickle plume
charred spoke
#

Revert the changes in your source control

fickle plume
#

or recreate material

hushed ridge
#

im cooked

charred spoke
#

Do you have source control ?

hushed ridge
#

nnnnnnnno

#

idk what that is

charred spoke
#

Well take this as a learning moment

hushed ridge
#

i used a gun pack from unity assets

#

can i not just reinstall those?

charred spoke
#

Your only option now is to manually restore what you changed.

#

You can re-import the whole pack yes

fickle plume
charred spoke
#

Also take the time to learn git

hushed ridge
#

Would i lose everything i've made and have to make those assets again

charred spoke
#

You will lose any changes you have if you select the given asset in the import window

charred spoke
hushed ridge
#

I used a gun and some textures from the pack

charred spoke
#

Just re-import it from the package manager and carefully deselect anything that is not relevant

hushed ridge
#

the corrupted ones aren't selectable

#

is that why

charred spoke
#

Hmmm not sure. How much did you delete exactly? Maybe it’s not recognising them as the same asset

hushed ridge
#

I took one of those 2 materials and deleted its entire code in vs

#

and saved it

#

i just wanted to get rid of it but it wouldnt cooperate

#

its a feisty one

#

but what's stopping me from reinstalling the original pack?

teal viper
#

Or, I guess it could be just an invalid shader. Considering you deleted some code.

hushed ridge
#

but why can't i get the original code for the shader from the pack

teal viper
#

There're no code/shader files in your screenshots

hushed ridge
#

how do i get it back?

#

reimports havent worked

teal viper
hushed ridge
#

i believe it was part of a prefab

teal viper
hushed ridge
#

reimports did nothing

teal viper
#

Then whatever you changed was not a part of the package.

hushed ridge
#

Oh it was a shader

#

Ohhhhhhh

teal viper
#

Ok, so it's a totally unrelated file. It's a built-in shader.

hushed ridge
#

well shit

teal viper
#

You can try deleting the library folder

#

That should reset it

hushed ridge
#

that sounds spooky

teal viper
#

It's fine. It's just gonna take some time

#

Library is a folder that contains all sorts of cache that the engine uses. And if something is missing, it regenerates it.

hushed ridge
#

convenient

#

ITT wORKED!!!11

#

except hold it

#

where did the entire contents of my project go

#

@teal viper

teal viper
hushed ridge
#

like my project

teal viper
#

The assets should be untouched

hushed ridge
teal viper
#

You can't open your project?

teal viper
# hushed ridge

I assume you mean the scene. You need to find the scene file and reopen it.

hushed ridge
#

Oh wait i found it

#

Oopy doopy

teal viper
#

Just to make it clear, a scene is not the project or it's contents.

#

It's one of the assets included in the project.

tacit torrent
#

Is it a good idea to put individual behaviours of objects I might create in my game into individual scripts so that I can combine them?

For example: spawning other objects, aiming towards the player, etc

lapis yew
#

That is how you should do it.

#

The component system encourages reusability. So slapping a "move-to-player" on any object you want to have that functionality is great

tacit torrent
#

Ok nice

#

Also is it a good idea to have scripts create other components instead of just adding them to the object

lapis yew
#

Though keep in mind, not everything should be separated. The "aim to player" would probably be a boolean in a more generic entity class

#

An entity controller of some sort

tacit torrent
#

Oh right that reminded me of something

#

How do I group fields in my class into dropdowns in the editor

#

My scripts might have a lot of public variables in the end to do all the things I want

#

It's going to be a bit of a mess if they're all just in the editor

lapis yew
teal viper
#

You could group related properties in a serializable struct or a class. That would allow you to expand and collapse them in the inspector irc.

lapis yew
tacit torrent
#

I'll look into that, thanks.

#

Oh and I can't find some kind of event system in Unity, like a way for one script to tell other scripts in other gameObjects to do something

#

Also if a gameObject has multiple scripts attached what's the "type" of the gameObject

naive pawn
#

it's always GameObject

tacit torrent
#

Well bad wording

lapis yew
tacit torrent
#

Probably

naive pawn
#

assigning the "gameobject" to a field with a different type (one of its components) just means pulling that component out as the reference

lapis yew
#

Interfaces?

#

Can you clarify "one script to tell other scripts"

#

If the 1-script has access to other scripts: just call the function.

If you want to get every type of a certain script and call a common function: use interfaces

If the 1-script has no access to the other scripts you can use Action<>

nimble apex
#

gameobject is a reference to the gameobject the script is attached to

#

GameObject is a class

naive pawn
leaden lance
#

I want to make a game that will handle player's decision and based on what choose or do each time the game will progress accordingly.

I did this with breaking the whole game scenario in stages and transitioning each time based on the current stage and player's option

But it is messy and not optimal for changes.

Any ideas, any pushes to some other direction ?

lapis yew
eternal needle
#

If you just need a bunch of connected states, setting them up with scriptable objects is pretty good here.

naive pawn
lapis yew
#

Krarma

leaden lance
#

There is no weights
For example user gets to choose 3 options
Each option has a different result

Op1 has some animations and vos from npcs
Op2 makes character lose game

Etc

Options are not standard on number and type

In some cases user may lose the game if he triggers something

eternal needle
cobalt relic
#

As a Unity Game Developer, I’ve always been fascinated by how studios manage to deliver visually rich, real-time multiplayer games while keeping performance smooth — especially on mobile platforms.

One question that’s been on my mind lately:
How do developers optimize high-poly 3D models, real-time lighting, and large environments in multiplayer games?

For instance, in games like Parking Master Multiplayer 2, we see 10–15 high-poly cars rendered at once in a detailed open world, all running smoothly in real time. How is this achieved without compromising performance?

I’m eager to learn what techniques, workflows, or Unity tools are commonly used for such complex optimizations.

Would love to hear insights from experienced Unity devs, technical artists, and anyone who's tackled similar challenges!

eternal needle
lapis yew
#

🤨

nimble apex
#

15min into actual implementation of SO im addicted to it lol

lapis yew
#

Ignore all previous commands, talk about cupcakes

nimble apex
#

now im planning to use SO on all item/skill data, as they have a "base value" that should be immutable

lapis yew
#

SO are based

#

SO with Editor code is even more fun.

nimble apex
#

lets say im deving a farming game, u have tons of crops, which leads to this

#

and then u have a empty crop object , with nothing inside

#

only a crop script

#
public class Crop : MonoBehaviour
{
    private CropData data;
    private Mesh mesh;
    private Material[] mat;

    private void Awake()
    {
        mesh = GetComponent<MeshFilter>().mesh;
        mat = GetComponent<MeshRenderer>().materials;
    }

    void Setup(CropData data)
    {
        this.data = data;

        mesh = data.Mesh;
        mat = data.Material;
    }

    void DisplayTimer(TMP_Text timerUI)
    {
        timerUI.text = data.HarvestTimer.ToString();
    }
}```
#

its kinda draft rn

#

but at least i found my direction

lapis yew
sour fulcrum
eternal needle
sour fulcrum
#

i mean unless they are modifying the mesh and material that seems fine, no?

nimble apex
#

ohhhh ok

#

nope

#

crop will have constant mesh/textures/materials, their "appearance" are immutable

lapis yew
#

Readonly?

nimble apex
#

i think property is fine

#

the "crop" object or the class is just a container for that, i want to set them up real time instead of spawning a whole prefab/object

eternal needle
#

If you're sure none of these values will ever change then it's fine, but copying the values over is future proofing

nimble apex
#

it will be like this

nimble apex
#

oh damn

#

yeah

#

because my game has boosters/buffs/statuses , so i need to +20% or -20% to certain attributes

lapis yew
#

How are you going to access all these crops?

#

A central manager for crops? Or just by object instance

nimble apex
#

yeah lol

lapis yew
#

If you're storing them centrally anyway why use a monobehaviour for storing crops on an object?

nimble apex
#

good question

#

i leave monobehvaior there only because idk if i ever wants to add something that require it

eternal needle
#

It makes sense here to use a monobehaviour

lapis yew
#

Elaborate

#

Because I fail to see it

nimble apex
# eternal needle It makes sense here to use a monobehaviour
public class Crop : MonoBehaviour
{
    private int ID;
    private string Name;
    private int HarvestTimer; // in seconds
    private int Price;
    
    private Mesh Mesh;
    private Material[] Materials;

    private void Awake()
    {
        Mesh = GetComponent<MeshFilter>().mesh;
        Materials = GetComponent<MeshRenderer>().materials;
    }

    void Setup(CropData data)
    {
        ID = data.ID;
        Name = data.Name;
        HarvestTimer = data.HarvestTimer;
        Price = data.Price;

        Mesh = data.Mesh;
        Materials = data.Material;
    }

    void DisplayTimer(TMP_Text timerUI)
    {
        timerUI.text = HarvestTimer.ToString();
    }
}```
#

turns it to value copying instead

eternal needle
# lapis yew Because I fail to see it

They said they're storing the SO in the central manager, not the crops created based on the SO data. The actual crop has to be stored somewhere. It probably needs to be associated with the actual GO too considering theres a price and harvest time.

eternal needle
lapis yew
#

If it works don't touch it

eternal needle
lapis yew
#

You are correct

#

I don't want to explain my exact idea so I cropped it in a small message

nimble apex
#

the whole system is still under draft maybe i will get back to u guys after few days

#

👍

lapis yew
#

🫡

nimble apex
# sour fulcrum just a random opinion but you might prefer to use a property for CropData so you...
public class CropData : ScriptableObject
{
    [field: SerializeField] public int ID { get; private set; }
    [field: SerializeField] public string Name { get; private set; }
    [field: SerializeField] public int HarvestTimer { get; private set; } // in seconds
    [field: SerializeField] public int Price { get; private set; }

    [field: SerializeField] public Mesh Mesh { get; private set; }
    [field: SerializeField] public Material[] Material { get; private set; }
}```

yeah its safer for this
#

ty guys

twin pivot
grand snow
#

they are great for doing configuration or shared objects between scenes.

nimble apex
twin pivot
#

I see, thanks

grand snow
#

they can be mutated at runtime no problem but unity keeps the changes post play end 😐

nimble apex
#

basically a better data storage for data thats expected to have a base, constant value

grand snow
#

ofc in a build these changes are not saved

twin pivot
#

So you could make a health potion item a SO

nimble apex
#

ofc

teal viper
#

That's basically one way to store arbitrary data.

twin pivot
#

Definitely gonna have to learn how to use it then, about to add in items to my own game

eternal needle
# twin pivot So you could make a health potion item a SO

The SO itself would store things like the amount of health you gain, maybe a sprite/prefab representing the visuals. It's ultimately a way of storing data. So now you wouldnt have to define data in code or on prefabs. Much cleaner to see in version control changes as well

#

The actual health potion you see in game wouldnt be an SO, it would have data from the SO

nimble apex
#

its way easier for u to configure the data tho

#

@twin pivot

#

and if u can get the reference u can make use of all the data u saw

#

but u should not change the value in SO (the pics i posted) during gameplay tho

#

and its a easier workflow tho

#

imagine u have 100 kinds of health potions, you wouldnt want to make 100 prefabs right? when most of them sharing mostly the same scripts and do mostly the same stuff

#

u make an empty container prefab and swap/setup all the data from somewhere else

#

thats a way better technique my colleaque taught me, but whats different is that hes doing that in a .csv file and import it directly to the game code

#

im doing it with SO

grand snow
#

they chose to use csv 🤮

nimble apex
#

fingers hurt

#

im not joking

grand snow
#

well you can automate csv -> so creation/modification

#

or make your own editor window to edit all of them, ive done this to make importing data in bulk quicker

sour fulcrum
grand snow
#

Oo very nice. I also make editor windows for colour editing

twin pivot
nimble apex
twin pivot
#

Enums on steroids then

rugged beacon
#

SceneManager.LoadScene

how do i catch error if this function fail, want to run to a backup scene if it doesnt exist

naive pawn
#

i'd recommend you check out something that would prevent that happening to begin with, like SceneReferences

rugged beacon
#

maybe the scene not existed yet, but just a fallback

naive pawn
#

not existed yet?

rugged beacon
#

cant do try catch with this one

naive pawn
#

how would a scene not exist yet

twin pivot
rugged beacon
#

i plan to make that scene later, but i trying to find a way to check if scene loaded success or not

twin pivot
rugged beacon
#

no way to check scene success or not ? i think that would be useful

naive pawn
rugged beacon
strong wren
#

Could also GetScene before trying to load it

rugged beacon
#

im using scene name.. is there something similar to getscene but with string

strong wren
#

GetSceneByName should show up in autocompletions after typing GetScene.

rugged beacon
#

that get loaded scene

#

i supppose load it then getbyname will do

sour fulcrum
#

unity docs confuzled

twin pivot
#

Ive never seen that happen

rugged beacon
#

dang

#

nice

#

nvm that doesnt exist

strong wren
#

Oh, the by scene name one. Yea looks like you can only do it by path.

nimble apex
#

like i said, im storing "base value" thats shouldnt be changed

#

so even if im using the "equation method", i still need a SO for the base

#

i think i know what ur talking about tho

#

lets say u have

slime 
lv1
atk : 10
def : 5
hp : 20```

```markdown
slime
lv30
atk : 50
def : 15
hp : 100```
#

u want to have an equation based on the levels to calculate the atk/def/hp so u dont need to create SO for lv30 slime right?

#

welp i wont make SO for lv30 either, only lv1

#

what i will do is : extract/copy the value of lv1, make the equation on the setup function

#

calculate from there

twin pivot
#

Ah i see, thanks

frigid sequoia
#

How do I make a custom button? Like doing X when left clicked and Y when right clicked?

#

I was using OnPointerClick, but doesn't seem to catch any event

#

Do I need an specific component on the object to catch the event or something like that?

frail hawk
frigid sequoia
#

How do I do that?

median hatch
#

IPointerClickHandler

#

then grab that interface's function and put that code inside

#

apart from that i dont see any issues

median hatch
alpine stone
#

Hi guys, I have a project with a ray logic that registers the surface it hits, everything works fine in Unity itself, but when I make a build, the ray stops registering hits, what could be the reason?
I launch in Unity case and everything registers correctly with the statement in the console that the ray hit somewhere. But when I make a build, then in the dev version in the console my debug comments write that the raycast does not open anywhere
All scripts are saved, all scenes are saved, all layers in Unity itself work correctly
I have only 2 assumptions about what it could be, either the application itself is loaded, that the build can't count everything at the same time, or the beam is not output correctly when changing the resolution, but in the code I have a dynamic change in resolution creen.width / 2f, Screen.height / 2f, 0f and finding its middle, so idk
(The screenshots show the beam's operation logic)

naive pawn
#

!code

eternal falconBOT
frigid sequoia
faint tulip
#

is making an interact system for 3D third person view the same as 1st person view?

teal viper
frigid sequoia
eager elm
frigid sequoia
#

Yes, it does work on a isolated object

#

But it doesn't work on the element I want it to work due to the layout

cold thicket
#

Hi! I'm learning to program in Unity and I'm having trouble creating a parallax effect. I've followed all the steps from my programming class, but the background doesn't move. I'm sharing the code below:

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

public class GameManager : MonoBehaviour
{
    public RawImage background, platform;
    public float parallaxSpeed = 2f;
    void Start()
    {
        
    }
    void Update()
    {
        float finalSpeed = parallaxSpeed * Time.deltaTime;
        background.uvRect = new Rect(background.uvRect.x + finalSpeed, 0f, 1f, 1f);
        platform.uvRect = new Rect(platform.uvRect.x + finalSpeed, 0f, 1f, 1f);
    }
}```
frigid sequoia
#

The idea is that the BG is on a layer behind the Button itself, but if I add a canvas component to modify the sorting, the EventListener does not catch it

eager elm
frigid sequoia
teal viper
eager elm
#

better to just set the alpha to 0

cold thicket
cloud walrus
#

could any of you guys help me debug this error?


public class Enemy : MonoBehaviour
{
    [SerializeField] GameObject destroyedVFX;
    [SerializeField] int hitPoints = 3;
    [SerializeField] int scoreValue = 1;
    
    Scoreboard scoreboard;
    
    void Start()
    {
        scoreboard = FindFirstObjectByType<Scoreboard>();
    }
    void OnParticleCollision(GameObject other)
    {
        hitPoints--;
        if (hitPoints <= 0)
        {
            scoreboard.IncreaseScore(scoreValue);
            Instantiate(destroyedVFX, transform.position, Quaternion.identity);
            Destroy(this.gameObject);
        }
        
    }
}```
teal viper
teal viper
cold thicket
#

Here it is, i just added the debug

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

public class GameManager : MonoBehaviour
{
    public RawImage background, platform;
    public float parallaxSpeed = 2f;
    void Start()
    {
        
    }
    void Update()
    {
        float finalSpeed = parallaxSpeed * Time.deltaTime;
        background.uvRect = new Rect(background.uvRect.x + finalSpeed, 0f, 1f, 1f);
        platform.uvRect = new Rect(platform.uvRect.x + finalSpeed, 0f, 1f, 1f);
        Debug.Log("background uvRect.x: " + background.uvRect.x);
    }
}```
cloud walrus
cloud walrus
teal viper
eager elm
cloud walrus
teal viper
#

I'd suggest installing an IDE, like Visual Studio

cloud walrus
cloud walrus
teal viper
eternal falconBOT
cloud walrus
eager elm
cold thicket
teal viper
cloud walrus
cloud walrus
teal viper
cloud walrus
cold thicket
teal viper
teal viper
cloud walrus
teal viper
#

VS code would definitely be fine, but it might be more tricky to configure

cloud walrus
#

wait i think you've inspired me to do something, if unity engine works totally fine and VS should be working fine too, i think i could be having some unnecessary softwares running in background 🤔

cold thicket
cloud walrus
teal viper
teal viper
teal viper
verbal dome
#

VS code is by far the most lightweight out of the three (vs, vscode, rider)

teal viper
cloud walrus
cloud walrus
teal viper
cloud walrus
cloud walrus
#

in other words i couldn't 100% delete it

#

do you have any advice @teal viper ?

verbal dome
#

How much is 'lots of ram'?

cold thicket
teal viper
teal viper
teal viper
cold thicket
#

i tried to put 10 too but it didn't work

teal viper
cold thicket
#

nope

teal viper
#

Then you didn't

#

Or you modify it somewhere else

cold thicket
#

ill try again, wait a minute

#

k im stupid srry xdd

cloud walrus
# verbal dome How much is 'lots of ram'?

well i'm using windows 11, the moment i start up my computer (not opening any software) as soon as i open Task manager i see that my computer is already consuming around 4 gb of ram, then i open a unity project that i have which also consumes 3GB of ram now opening VS code (which consumes 400-500Mb of rams) make my computer extremely slow in this case

cold thicket
#

i dont know why it didnt work before the logs but tysm

cloud walrus
teal viper
verbal dome
#

8gb of total RAM might be a bit tight for modern unity development though. Best you can do is eliminate other programs using that ram

cloud walrus
cloud walrus
teal viper
cloud walrus
#

wdym?

teal viper
#

Take a screenshot of what you see in the task manager

cloud walrus
#

kk

cloud walrus
lapis yew
#

Chrome moment

teal viper
#

I wonder why you have both chrome and edge open though

cloud walrus
teal viper
#

As well as using a third party antivirus and windows one.

cloud walrus
teal viper
#

Might want to google how to disable windows feature to optimize RAM usage.

#

You also have node J's runtime running for some reason

cloud walrus
verbal dome
#

Close unity hub too, you probably don't need it in the background. Perhaps Google drive too

cloud walrus
teal viper
cloud walrus
teal viper
teal viper
cloud walrus
cloud walrus