#💻┃code-beginner

1 messages · Page 694 of 1

hybrid wagon
#

good god

sour fulcrum
#

are you running set on the clone..

slow idol
polar acorn
#

Maybe show the full !code of the Projectile

slow idol
polar acorn
#

Oh, bot isn't working

sour fulcrum
#

Will Unity instansiate copy non-serialized values at runtime?

#

eg. if layer is private and not marked with SerializeField i wonder if that wont copy

polar acorn
slow idol
#

this will make any experienced programmer cry, so be careful

hybrid wagon
#

would do you some good to have comments certainly

polar acorn
#

just use this

hybrid wagon
#

also, with c#, you dont need dedicated getters and setters, that can be done when you define a variable

slow idol
hybrid wagon
#

inline and is a lot prettier

polar acorn
#

And instead of GameObject clone = Instantiate(gameObject), just do Projectile clone = Instantiate(this)

slow idol
#

i thought about doing that but was worried it might then miss data from other scripts

polar acorn
#

It won't

slow idol
#

which i guess is ironic considering that it seemingly made me miss out on data from the projectile script

polar acorn
#

It'll copy over any serialized data from all components on the object and just return the type you gave it

polar acorn
#

If not, it's never getting set

slow idol
#

not anymore, no

slow idol
polar acorn
#

Then that'd be why

polar acorn
slow idol
#

wtf

#

but then it spawns 3 of them 😭

polar acorn
#

How is it supposed to copy over a value that it literally cannot read or write to another object?

polar acorn
#

You should probably make these variables all [SerializeField]s instead of having all these setter functions

hybrid wagon
#

you can cut about 50 lines of bloat just by using inline getters and setters

polar acorn
#

And another 50 by storing GetComponents in Awake instead of re-getting them

#

If you have a public GetLayers and a public SetLayers you should just make layers public

hybrid wagon
#

true, its also just bad practice to continually retrive components instead of storing in memory

polar acorn
#

or use a public property

slow idol
#

why was i perpetually told to never use public variables

hybrid wagon
#

you can define variables like this:

public LayerMask layers {get; private set;} if you wanted it private

polar acorn
#

you're just doing it with extra steps

woeful scaffold
#

Whattt i always use public and always set an instance so i can use it

hybrid wagon
#

using public is fine; if youre doing it for the right reason

woeful scaffold
#

is that bad?

polar acorn
#

if you're gonna make the data publically accessible for reading and writing you might as well just make it public

hybrid wagon
#

since youre accessing that data outside of the class, public is perfectly fine

sour fulcrum
polar acorn
#

or use a property:
public LayerMask layers {get; set;}

hybrid wagon
woeful scaffold
polar acorn
hybrid wagon
#

whatever else

woeful scaffold
#

Serialize?

hybrid wagon
#

]oops

sour fulcrum
#

[field: SerializeField] public MyType MyPropertyName {get; private set; }
allows you to serialize a value while having it publically readable, but privately writable

woeful scaffold
#

ooh

hybrid wagon
#

serializefield just makes it visible in the inspector

polar acorn
woeful scaffold
#

so im gonna make most of my stuff private lol

#

what if i want to access that value in a different script?

hybrid wagon
#

cool thing about properties is you can also write more bits of inline code instead of just (accessability) get;

frigid sequoia
#

Is there a way to like simplify this like with a method call or something? Like, get me every item on each of the sublists

hybrid wagon
#

you can do get { bla bla bla return x; }

slow idol
#

are public variables automatically serialized

polar acorn
sour fulcrum
woeful scaffold
#

if its private how can i access it in a different script? i usually make it public and set an instance for the script

woeful scaffold
#

is there a better way other than making it public

polar acorn
#

That's what private means

woeful scaffold
#

i see

slow idol
#

man fuck programming

#

stupid ass

frigid sequoia
polar acorn
#

The code does exactly what you tell it to do. Nothing more, nothing less.

woeful scaffold
#

so public if i want to access it in a different location
private if i want it to stay inside that class

slow idol
#

THE HYDRA MISSILES WORK

#

THEY WORK

#

😭 thank you

woeful scaffold
#

np

slow idol
#

not you bozo lmao 💀

woeful scaffold
#

😹

slow idol
#

ikyk

sour fulcrum
frigid sequoia
#

l => l? Is that a reference to itself?

woeful scaffold
#

so many list

sour fulcrum
#

l here is a reference to the lists inside listList

polar acorn
# frigid sequoia l => l? Is that a reference to itself?

It's a function that returns its input. SelectMany takes a function that is meant to return the objects you want from the list. Normally, you'd give it a condition, like "Anything where this variable is true". But in this case, you just want everything. It'll give you an enumerator over every item in the nested lists

frigid sequoia
#

So lets say I would want it to give me just the items that have item.gearType == GearType.Weapon. Can I do that?

sour fulcrum
#

You can chuck in a Where()

        foreach (string listValue in listList.SelectMany(l => l.Where(s => s == "Thingo")))
        {

        }
#

(and l and s here are local variables, they can be named whatever you want)

frigid sequoia
#

Yeah, I don't get the arrows pointing at nothing at all lol

sour fulcrum
#

Yeah forsure, I found them very confusing at first too, it's basically a contextual micro function

frigid sequoia
#

Like I read this and get like no info at all out of it

ivory bobcat
polar acorn
sour fulcrum
#

I know memes are not the vibe here but it really is just

frigid sequoia
#

Basically the => is doing like.... this member returns this expression?

polar acorn
#

The stuff to the left of the => are the inputs. The stuff to the right are the outputs.

frigid sequoia
#

I just don't get why would u need an input, specially if the output is exactly the same as the input

polar acorn
ivory bobcat
#
int GetInt(int i)//Regular ol function
{
    return i;
}``````cs
int GetInt(int i) => i;//Expression bodied``````cs
(i) => i;//Lambda where for every parameter i, return i```
frigid sequoia
#

Like does nothing

polar acorn
#

a null function would be one that returns null

ivory bobcat
#

Use case: (return only values less than 5)cs int[] values = {0, 2, 6, 3, 10};Using Where( i => i < 5) would return the values {0, 2, 3} as an Enumerable that would be iterated by the foreach.

frigid sequoia
polar acorn
#

And putting them in the resulting collection

#

Then, you loop over that collection

frigid sequoia
#

But why is Where also asking for a function? Like, doesn't it need a condition? Shouldn't it just be a bolean and be s == "Stuff"??

polar acorn
#

Instead, it calls the function on every element in the collection, and if the result is true, it puts it in the list

ivory bobcat
frigid sequoia
#

So, I need to basically pass it a function that returns a bool, right?

polar acorn
#

It doesn't need to be a lambda, you can use a real function as well

frigid sequoia
#

So, this is a valid thing I can do? Is this right?

polar acorn
#

It compiles. Should probably do what you expect but I don't know what's in any of those lists

ivory bobcat
frigid sequoia
#

I want to hide all the items that do not appear on the HasSet "gearToShow"

#

From each of the items on each of list of "allGear"

ivory bobcat
#

Hmm, maybe you should just hide them when removing the item from the gearToShow collection instead of iterating like this on the side?

#

Or if they are added to the gearToShow collection at some point, all gears inactive and set to active when added to the collection.

sage peak
#

Hey guys! Where do I ask questions about lighting?

frigid sequoia
#

I think I had a reason as to why not just hide it directly, but I can't think about it right now

ivory bobcat
frigid sequoia
#

I think it was so I could iterate better for the items that are actually currently showing just in case

#

But since I changed that to a HashSet maybe it's not even that good of an idea anymore

ivory bobcat
sharp solar
#

holy balls GPUs are fast bro

#

2000 frames of 64x64 IR seeker simulation
then mip mapped to 1 dimensional audio signal
all within 2.3 ms

worthy jolt
#

I have an editor bug in the collision matrix I cant resolve. I've tried restarting unity and the computer. Seen this one before? Know how to fix it?

#

why laughing?

wooden hill
prime tartan
#

am making a 2d geometory dash type game will cinemachine be better for tracking or direct script

sharp solar
prime tartan
#

that dosent show anything 💀

wintry quarry
#

Also scripts and Cinemachine are not mutually exclusive

prime tartan
#

but my character is jittering is it cuz cinemachine or just movement

#

am using a slerp for movement too still

#

like its going back n forth bw pixels but moving

wintry quarry
#

Or that your code is breaking the interpolation

prime tartan
#

so if i do interpolation it wil be fine?

#

i thought i was rando rigidbody function

wintry quarry
#

If you do interpolation and your code doesn't break the interpolation

prime tartan
#

i didnt knew it was an important thing leme try

wintry quarry
#

What do you mean by this

prime tartan
#

for rotation

wintry quarry
#

It's possible your code is directly modifying the Transform, if so it will break interpolation

prime tartan
#

am making player face mouse with slerp

#

its interpolate still jittering

#

do i remove slerp

wintry quarry
#

If you're doing so via the Transform that's the problem

#

You cannot touch the Transform directly

prime tartan
#

transform.up for rotation and rigidobdy.linervelocity for movement

wintry quarry
#

Yes that's wrong

prime tartan
#

oh

#

but its working though

wintry quarry
#

Don't touch the Transform for a Rigidbody or it will break the interpolation

#

Working but without interpolation

prime tartan
#

ya

#

then i move using transform too?

wintry quarry
#

You need to rotate via the Rigidbody

prime tartan
#

oh

wintry quarry
prime tartan
#

ok i wil try thanks

#

will rb.moverotation do it?

wintry quarry
#

That's very tricky to use for mouse rotation

#

Because it can only go in FixedUpdate

#

Easier to directly modify the rotation property

prime tartan
#

oh

#

but u just told me to not use transform

wintry quarry
#

Correct

#

Use the Rigidbody

#

Rigidbody.rotation

prime tartan
#

ok leme try thx

#

i did with rb.rotation but now my player is not going forward at that angle

prime tartan
#

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
public float speed = 50f;
private float targetAngle = 0f;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
    rb.interpolation = RigidbodyInterpolation2D.Interpolate;
}

void Update()
{
    Vector3 mousePosition = Input.mousePosition;
    mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
    Vector2 direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);

    float angle = Vector2.SignedAngle(Vector2.right, direction);

    if (Mathf.Abs(angle) < 80f)
    {
        
        targetAngle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90f;
    }

    Debug.Log(angle);
}

void FixedUpdate()
{
    // Move the player in the direction it is facing (up after rotation)
    rb.linearVelocity = rb.transform.up * speed;
    rb.rotation = targetAngle;
}

}

#

this is what am using all is fine but if i get my mouse on the back side it changes the player's positon in relation to cinemachine

#

i might be asking yall too much but bro the last project i worked i searched all on the internet and then finally i quitted cuz of the bugs and not having solution after pouring like 8 hours

frigid sequoia
#

I am pretty sure you are just gonna tell about SO, but can I like get info from a prefab without needing to instanciate it?

frigid sequoia
#

Oh, can I? Like get the icon of something that is not in scene?

north kiln
#

I'm not sure what that means exactly, but sure, it exists, you can access it

frigid sequoia
#

It's... hard to explain. Basically items have a prefab that holds their info and also is like the main functions that allow to click them and move it around to equip them and all while in the inventory. I want to still be able to show that info in things that refer to a item but are not really an item that is in the inventory

strong sorrel
#

Im trying to use the new unity input system. I have the notification mode set to "Send messages". I use this function below to capture if the user is spriting. However, the game starts as not sprinting, then when I click shift the game recognizes sprinting. But when I let go of shift, it doesn't untrigger and still says its sprinting. Why is this?

public void OnSprint(InputValue value)
{
    isSprinting = value.isPressed;
}
#

Just @ me if anyone has a solution or a fix

undone pier
#

i am not getting OnTriggerEnter2D if i setActive(true) and object while standing still

#

if i move and setActive(true), the event trigger

#

anyone encountered this b4?

queen adder
#

How do you guys handle the lack of confidence in coding ? I keep rechecking the same damn code even though i already recheck it 10+ times before

polar acorn
polar acorn
queen adder
fierce shuttle
# queen adder Yeah i know but the class is so big that i cant remember every part of it so the...

If theres a bug somewhere, youll know in one of 3 ways - either the console will tell you about it at runtime (runtime error), or the console and your IDE will tell you about it before your code can be compiled (compilation error), or youll notice your game is not behaving in the way you intended (logical error), the latter is probably the hardest to deal with but you can use Debug.Log statements (or breakpoints) to get an idea of whats going on when unintended behaviour happens

In terms of having a big script, certainly breaking it down into smaller scripts and making sure that each of your classes are not doing more than they need to (for example, a UI script doesnt need to do any input management), but that will come with time, and getting more familiar with S.O.L.I.D and code patterns (which as a beginner, I think its more important to get things working first in a way you understand)

queen adder
#

Luckly it wasnt public API so no backward compatibility breaks

fierce shuttle
queen adder
#

i learned a lot from that but also gave me this anxiety lol

naive pawn
north kiln
#

you have to push through, because only with experience will you get good enough. If you're fretting over everything constantly, you're not going to make things. Mistakes are how you learn, you have to do things so you can learn from them

queen adder
#

Okay thanks everyone

naive pawn
#

lack of confidence isn't lack of competence, and same for the inverse

#

check your work instead of the direct code you write
does it work? are you able to debug? are you able to find info if you need it? etc

north kiln
#

I'm an anxious person and it's taken a long time to not to refactor as much, and it's still a constant battle to avoid falling into redoing work

naive pawn
#

i think everyone goes through spaghetti code a few times at first lol
great first-hand lesson on why you should put some thought into structuring the project

queen adder
#

Ok thanks everyone i had to do something irl

naive pawn
#

(and hey, arguably underconfidence is better than overconfidence)

fierce shuttle
#

^ true, its better to assume you CAN improve, than to assume you already know everything (even if you made several games before)

median hatch
sour fulcrum
#

Also just in general, learning a whole new language is hard, learning programming is hard. Anyone trying to pick it up is gonna struggle and spending the effort to learn a new skill is something to be proud of 😄

eternal needle
# queen adder Yeah i know but the class is so big that i cant remember every part of it so the...

ive found a few minor bugs so far in a major enterprise system thats been out there for 20 years. practically every game has their own "bug abuse" community too. hell I even played some games particularly for the exploits.
These things happen. As software grows, so does the possibility for edge cases, especially in a game where you have a ton of systems intertwined. The most you can do is test features as you make them. Experience is what leads you to knowing what to test sometimes.

median hatch
#

not fully sure what you meant but maybe static variables would work here no?

median hatch
jovial grove
#

hi, im trying to make a game about a spaceship with planet physics. How would you align the players rotation with the orbit of the planet

frail hawk
#

planetary gravity is the keyword you are looking for

frail hawk
worn peak
dusk arch
#

hello, I made a player walk, is the code good? xd
using UnityEngine;
using UnityEngine.InputSystem;

public class Movement : MonoBehaviour
{
public float velocidad = 5f;
private Vector2 movimientoInput;
private Rigidbody2D rb;
private PlayerInputActions inputActions;

private void Awake()
{
    inputActions = new PlayerInputActions();

    inputActions.Player.Move.performed += ctx => movimientoInput = ctx.ReadValue<Vector2>();
    inputActions.Player.Move.canceled += ctx => movimientoInput = Vector2.zero;
}

private void OnEnable()
{
    inputActions.Player.Enable();
}

private void OnDisable()
{
    inputActions.Player.Disable();
}

private void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

private void FixedUpdate()
{
    Debug.Log("Input: " + movimientoInput);
    rb.linearVelocity = new Vector2(movimientoInput.x * velocidad, rb.linearVelocity.y);
}

}

dusk arch
#

Well, it can only move left and right xd. I'm asking because in the tutorials they make the player move with much less code.

frail hawk
#

it can only move left and right because you did not define it to do somethign else

#
 rb.linearVelocity = new Vector2(movimientoInput.x * velocidad, **rb.linearVelocity.y**);
naive pawn
#

that part is correct though

#

(also for emphasis in code i'd recommend an arrow on the next line)

frail hawk
#

maybe they want to move up and down too (some kind of 2d top down)

naive pawn
#

oh good point, ive been doing sidescroller for way too long

dusk arch
naive pawn
#

doesn't matter at this scale

dusk arch
#

and why there's a private before the void ....¿

naive pawn
#

don't worry about perf until one of these two things happens:

  • you start having perf issues
  • you start counting in thousands or millions
naive pawn
dusk arch
#

Yeah, I really don’t know the difference between public and private.

naive pawn
#

public means any other class can access the member
private means no other class can access the member (it can only be used within the same class)

#

the default access level is private (there are also 4 other levels aside from these 2) so technically it isn't required but i suppose it's there just to be explicit

dusk arch
#

ohh okok, thx so muchh

naive pawn
#

a few keywords to google for further reading, "access level"/"access modifier"

dull grail
#

How can i add component by string with it's name? I've tried to use AddComponent() but ide throwing error saying this method obsolete and AddComponent<>() throwing error bc cannot resolve class name

var itemClassName = itemData.GetRespectiveClassName();
var itemScript = item.AddComponent<itemClassName>(); // cannot resolve
var itemScript = item.AddComponent(itemClassName); // obsolete
hexed terrace
#

you shouldn't be using a string

silk night
naive pawn
#

if you have the class you should just use the generic one

naive pawn
silk night
#

Well seems that he wants to get that dynamically so he cant use the generic type

dull grail
#

I want to use scriptable object with respective class on object, like class Item and ScriptableObject ItemSO so my target is to get type dynamically and paste it to the object

silk night
#

How are you saving the class item in the scriptable object? Just as a string?

naive pawn
#

you would do instance.GetType() in that case

woeful scaffold
#

I'm losing my MIND, when I grab my weapon's prefab onto my weaponslot in the player's hand, it is fixed perfectly (0, 0, 0) and when i try to do it by code it just give me some weird x y z

#

i tried resetting it in the code, still weird

woeful scaffold
#

the prefab itself was a mesh at first, so i added a parent to it, in hopes of maybe fixing it

naive pawn
#

keep in mind that the position shown in the inspector is the localPosition, not the position

naive pawn
dull grail
# silk night How are you saving the class item in the scriptable object? Just as a string?

I'm using scriptable object to store default item data and when object already exist somewhere in the world i store it in class so i can modify in one way or another

public void CreateItem(InventoryObjectSO itemData, int amount, Vector2 position)
    {
        GameObject item = Instantiate(itemPrefab, position, Quaternion.identity);
        item.name = itemData.itemName;

        var itemClassName = itemData.GetRespectiveClassName();
        var itemScript = item.AddComponent<itemClassName>();
        var itemScript = item.AddComponent(item.AddComponent(typeof(itemClassName));
    }
woeful scaffold
#
{
    DropCurrentWeapon(pickedUpWeapon);

    // Parent it to the weapon slot
    pickedUpWeapon.transform.SetParent(activeWeaponSlot.transform, false);

    // Reset transform to be at (0,0,0)
    pickedUpWeapon.transform.localPosition = Vector3.zero;
    pickedUpWeapon.transform.localRotation = Quaternion.identity;

    // Mark it active
    Weapon weapon = pickedUpWeapon.GetComponent<Weapon>();
    weapon.isActiveWeapon = true;
}```
naive pawn
dull grail
#

How should i do it else?

silk night
#

Do you have very few types that rarely change?
If so you can do an enum -> type mapping

naive pawn
#

so you have an inventory and individual slots?

woeful scaffold
#

perfect when its 0,0,0 manually grabbed onto the slot

#

wtf?

dull grail
#

Inventory store slots and each slot store object with data

naive pawn
silk night
naive pawn
#

you could just have InventoryObject have a field of type InventoryObjectSO, no need to paste anything anywhere

woeful scaffold
#

I havent checked what coordinates the code brings me

#

i look at the inspector and it has different x y z when it links it uip

dull grail
#

At this point i have only 1 SO but what i wanted is to branch it later, like inventoryObject is base script, then goes something like weapon -> rifle -> specific weapon and trying to make it scalable from now

naive pawn
#

have variance in the data held, not the data holder

silk night
woeful scaffold
#
{
    if (activeWeaponSlot.transform.childCount > 0)
    {
        var weaponToDrop = activeWeaponSlot.transform.GetChild(0).gameObject;

        weaponToDrop.GetComponent<Weapon>().isActiveWeapon = false;

        weaponToDrop.transform.SetParent(pickedUpWeapon.transform.parent);
        weaponToDrop.transform.localPosition = pickedUpWeapon.transform.localPosition;
        weaponToDrop.transform.localRotation = pickedUpWeapon.transform.localRotation;
    }
}```
silk night
dull grail
woeful scaffold
#

weapontodrop is the current weapon im holding

#

i want to de-parent it

#

so its not a child of my slot

silk night
#

ah wait, didnt see the .parent, if you wanna fully deparent you can just do SetParent(null)

woeful scaffold
#

yeab but i'd rather it be a child of the world instead

#

so it'll just be chilling

silk night
#

ah alright

naive pawn
# dull grail Can you elaborate? Can't catch your thought

consider:
rename InventoryObject to InventorySlot
then inside, have a field for InventoryObjectSO (or perhaps rename that to InventoryItem/SO or something)
you could have the SO or an interface have a virtual Use method, then a specific kind of item, like InventoryWeapon or whatever would extend the SO and implement the Use method (or also implement the interface with that route)

woeful scaffold
#

i still dont get how my issue persists

naive pawn
#

@woeful scaffold what even is your issue?
what's the behavior you're seeing from code that you don't want?

silk night
#

i would assume you don't do anything in the setter for IsActiveWeapon? (except for setting the bool)

naive pawn
#

also, you should probably just store the Weapons yourself instead of using the transform children and then having to GetComponent each time

woeful scaffold
naive pawn
#

that being AddWeaponIntoActiveSlot, correct?

dull grail
woeful scaffold
#

yes

naive pawn
#

so if you inspect the gun, you see it not at 0,0,0?

woeful scaffold
#

if its by code ,yeah

naive pawn
#

have you verified that you've saved and recompiled the code with the position setting

woeful scaffold
#

i restarted unity to be sure i guess

naive pawn
#

that doesn't verify that you've actually saved the code

woeful scaffold
#

i did ctrl s and i saw unity loading

#

i assume that saves the code

naive pawn
#

right, that would do it

woeful scaffold
#

the method itself is working but the xyz doesnt align well

#

im not sure what's causing it

naive pawn
#

in AddWeaponIntoActiveSlot, try adding some logs
pickedUpWeapon.name to make sure you're targetting the right one, its localPosition and localRotation after you try to set it

naive pawn
woeful scaffold
#

wait i wanna take a vid to show u

#

its acting up

#

@naive pawn SO like

#

I press play right, i spawn in as the character, the weapon that i pick up is aligned related to the world position

#

so if there's a weapon a little bit forward than the middle of the world, when i pick it up it'll be forward

#

if its perfectly in the middle, then when i pick it up its placed correctly in the hand

#

wth

naive pawn
#

im not psychic, i have no idea what you're talking about lmao

woeful scaffold
#

ill explain better

#

the cube/volume icon is the middle of the world

#

u see the pistol thats slightly on the left and forward?

#

if i pick it up, its on the left and forward just like it was placed originally

naive pawn
#

what is the issue

woeful scaffold
#

it's not being placed fixed in my hand, it's being placed on my hand + the offset of the world or something

naive pawn
#

if you inspect said weapon while it's not in your hand, does it show 0,0,0 or something else

woeful scaffold
#

you mean the prefab of it?

#

or the ones placed on the ground

naive pawn
#

the gameobject of the weapon that's supposed to be in your hand

woeful scaffold
#

the weapon on the ground that i want to pick up has the X value of 0.317 and z 0.811, when i pick it up it keeps that value

#

i want it to reset when i pick it up

naive pawn
woeful scaffold
#

oh ill dot hat now

atomic prairie
#

hey guys new to unity, i tried following brackey's unity github setup video, am i supposed to have this many changed files?

keen dew
#

No. You're missing a .gitignore file or it's in the wrong place

#

or the git project root is wrong

woeful scaffold
#

Figured it out

#

its the animator

fierce knoll
#

no, though most of the ones in that snippet are fine. When you setup a GH repo you get a chance to choose a template gitignore

atomic prairie
#

i swear i picked the unity gitignore file, its in my repo as well, lemme screenshot it rq

fierce knoll
#

yeah I keep templates of the ignore and attributes in my GH shared repo

atomic prairie
#

oh wait nvm yeah the root was just wrong

#

i moved the gitignore file and it works now lol

#

thanks guys

uneven lodge
#

Can I submit my coding problems here ?

slender nymph
#

Did you read what the error says?

uneven lodge
#

yes

slender nymph
#

Okay so have you tried changing the setting mentioned in the error?

uneven lodge
#

where is it

#

I can't find it

#

like frfr

slender nymph
#

gee, if only the error message told you what the setting is called as well as where it is. since you didn't read it we'll never know

grand snow
#

Its almost worrying how many people post that error here without READING IT

arctic river
#

wsg gng

#

aw

slender nymph
#

!collab 👇

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

arctic river
#

oh

crisp lodge
slender nymph
#

you'll also want to provide more details about the issue (see #854851968446365696 for what to include when asking for help)

slender nymph
rancid anchor
#

@slender nymph ty i will move post on there

red igloo
#

I am making this feature where when the player which is the ball goes into the trigger zone and presses R I want the Tracking Target to switch to Player 2 which is the cube. I haven't touched cinemachine for a while so I have forgotten some stuff. How would I go about this?

Here is my script and this is what I got so far. > https://paste.ofcode.org/NFwcKegivjZjA6a9fGKhCW

rough granite
wet vector
#

hello, is wheel collider's source no longer online?

wintry quarry
wet vector
#

Yes, someone once shared a pretty solid base that was the equivalent of the wheel collider. but this is more available

wet vector
#

That's right, I'd forgotten about it. Thanks, if I'm not an idiot, Unity's wheel collider is based on that.

lime mesa
#

i need a bit of help, im currently stuck finding an unsupported shader, however i have no clue how or where it could be. is there any way to make it a bit easier to find? (im sorry if this is the wrong channel to ask this in, i had no clue where else to ask)

grand snow
rich ice
#

!code

eternal falconBOT
terse saddle
#

hello, I just started learning Unity, I have an idea for the game
I started developing with basic movement but ran into a problem with implementation on inclined surfaces
the problem is that when the surface is tilted even by 30 degrees, the player can freeze at a spontaneous moment
here is the code for implementing movement

I am translating through Google Translate, there may be errors in translation
https://paste.ofcode.org/3LqWQVsrzBFuzVdWqGiBaT

slender nymph
#

rather than just setting a Y position for your target and still moving with the same X and Z, you should instead use the normal from the ground (provided by the RaycastHit) and project your desired movement on a plane represented by that normal. It will get you the correct movement direction.

terse saddle
#

could you please tell me how to do this or even send me the edited code?

slender nymph
#

you're also breaking the rigidbody's interpolation by setting its position each time you call SetY as well as when you set its rotation in the loop which can lead to stuttery movement

round cove
#

oh sh yeah sorry

terse saddle
slender nymph
#

what do you mean by "a strictly defined position relative to the raycast point"

terse saddle
#

I mean the distance from the beam landing point should be 2f

#

something like that but without breaking a rigidbody

if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit))
{
    Vector3 point = transform.position;
    point.y = hit.point.y + _height;
    transform.position = point;
}
slender nymph
#

you would just apply any normal gravity and stop it at the ground as normal. then your movement would be projected along the ground so you won't have to manually set the Y position

wintry quarry
terse saddle
#

It's just by design that part of the object can end up in the textures, so the center of the object ends up on a point, and if you use a rigid body, it will hang unattractively when the rotation axes are frozen.

#

Should I try writing a basic collision and movement system myself?

red igloo
#

I was wondering how I can change the tracking target depending on the gameobject list I know its something like _camera.follow blah blah but I want it to track the current target index (e.g., 0 for main player, 1 for player2). how would I do it? this is what I got so far and its working perfectly right now https://paste.ofcode.org/4SM56vLh5GQ5542FE4j47z

frail hawk
#

you´d have to change the cinemachine Follow target

red igloo
#

I will be adding multiple cubes where you can change

subtle mirage
#

Assuming that is how you would set the references/arguments in the first place of course

red igloo
#

so I want it to work with multiple players/switcherzones.

#

I am soo confused at this point lol

frail hawk
#

please explain clearly what you want to do.

red igloo
# frail hawk please explain clearly what you want to do.

Sorry its hard to explain lol. Basically I want it so when I go in the trigger zone the player 2 or 3 depending on which trigger zone I am in should be placed in the list as you can see in the video and when I press R it should switch the player to the one that's it the list and I want this to work with multiple players. get it?

red igloo
frail hawk
#

well you can have one variable for the target and change that as you wish.
Transform target; << this can be changed somewhere in your code, anytime you want.
camera.follow(target)

#

you can also fill your List before runtime if the transforms are existing and known

red igloo
#

tbh completely honest I am so confused lol been at this for the whole day

#

So first how would I make it so when I am in the triggerzones it correctly gets the right object and places it in the list?

subtle mirage
strong sorrel
frail hawk
#

there is a reason why these special channels exist

subtle mirage
# red igloo assistance

In that case, there a couple ways you could do it.
The most obvious would be making another variable for the player3 exactly how you setup the first for player2 and just add an if condition.
However, if you want this more dynamic to allow for more targets in the future, I suggest having a class on the zone, that the switcher looks for, with a reference so the switcher can read/use it on enter/exit.

#

How you set that reference is however you want to do it
Could be in the inspector, or even just moving the current find object code to the new class

red igloo
#

wdym class on the zone? like make a separate script and make it a public class?

acoustic belfry
#

why exactly shouldn't be used physics movements on Update?
what if i must only use update or fixedupdate

polar acorn
red igloo
# subtle mirage Yes

so in the new script for the zone switcher what should be in it? ontrigger enter/exit?

unique depot
#

Im new to using the profiler, I found what code is using so much gc alloc, but not sure how to fix it

#

Anyone willing to help?

subtle mirage
#

In the zone class, you'll have a public reference/variable for the object you want to add to the list

naive pawn
#

show said code, perhaps

unique depot
#

whats the way to post it without being so messy?

naive pawn
#

!code

eternal falconBOT
unique depot
#
public override void CheckForTransitions()
{
    // All the transitions between states are defined here
    switch (currentState)
    {
        // Transitions from Wander to other states
        case Wander:
            // If is not alive aka dead
            if (!isAlive)
            {
                // Transition to the Death state
                SetCurrentState(new Death(this));
            }

            // If the player is not being attacked by another zombie and the player is within the attack distance
            if (PlayerIsNotBeingAttacked() && Vector3.Distance(transform.position, player.transform.position) <= attackDistance)
            {
                SetCurrentState(new Attack(this));
            }

            break;
        // No transitions needed for Death because once the zombie is dead it doesn't have to transition to any other state!
    }
}
naive pawn
#

also Attack as well

unique depot
red igloo
#

so in the new script I should add what you put?

#

Sorry for bothering you lol been at this for the whole day still kinda confused

naive pawn
unique depot
naive pawn
#

the garbage basically boils down to instantiating a ref type
you could either make it not a ref type or not instantiate a bunch
the former would be turning it into a struct
the latter would be only instantiating the states once and then reusing them
you could also do both, like you might do with enum states

unique depot
#

Ill try only instantiating the states once and then reusing them

#

i also researched that Vector3 uses some too, is this true?

naive pawn
#

uses some.. what?

subtle mirage
#

As I mentioned, you'll be adjusting the the OnEnter/Exit already present in the current switcher script.
However, you'll be moving the variable for the object to be added to the list into the new script.
After checking for the zone, you look for and use that reference.

In the new script, if the reference is public GameObject ObjectToAdd
Then you'll use zone.ObjectToAdd instead of player2.

What you'll need to figure out is how you want to set that reference in the new script. Though I would suggest setting it in the inspector by dragging in the object from the scene that you want to use for that zone.

subtle mirage
unique depot
naive pawn
#

no, Vector3 is a value type.

unique depot
#

Im trying to get GC alloc to 0%

naive pawn
#

that's not possible

#

every component is a ref type

#

gameobjects too

#

you will have ref types -> garbage -> gc

subtle mirage
#

sure it's possible
Application.Quit()

naive pawn
#

optimization is reducing unnecessary allocations, not removing them outright, because some are necessary

unique depot
#

For this project, I have too

naive pawn
#

do you have a gameobject in your scene?

unique depot
#

Let me rephrase, for these scripts, I have to have 0% gc alloc

naive pawn
#

lofty goals will get you nowhere

#

gc is not something to be avoided

#

you should be thinking about unnecessary gc, not allocations as a whole

polar acorn
unique depot
#

Im just telling yoy what the project requierments are

naive pawn
#

you sure?

unique depot
#

yes I am sure

eternal needle
#

depending on the goal its definitely possible. Usually when people say 0 alloc, they just mean allocated once at the start and none afterwards while playing

subtle mirage
#

I think the goal here is to perform the task without creating new references per frame

naive pawn
#

this is extremely unreasonable for a project, unless it's something really low level
but at that level you probably just don't have a gc

unique depot
#

It is very low level, im just leaning how to use a profiler

eternal needle
#

the deep profiler would also give you more insight as to what specifically is allocating, though we can see those new Death and new Attack directly do so. You cannot get around this, you must change how this works if you want to avoid allocation there. Or reuse the attack/death state

naive pawn
#

i don't think "profiler" and "low level" really fit in the same sentence

unique depot
#

ok

naive pawn
#

i feel like you're just trying to use cool jargon without actually understanding the nuances...

naive pawn
polar acorn
eternal needle
#

depending on what they're actually tasked with, it could be very reasonable to expect that certain scripts dont allocate anything after they start up

subtle mirage
naive pawn
naive pawn
eternal needle
polar acorn
#

"0 garbage collection" literally means no reference variables. And that includes Unity-defined ones so it can't be a MonoBehaviour either

polar acorn
eternal needle
# unique depot this is exactly what I mean

Id start with looking at why you need to new a state in the first place. You will need to reuse these states instead and declare it once, possibly in awake. if you have allocations past that, then you should also use the deep profiler. its just a button on the profiler

naive pawn
unique depot
#

!code

eternal falconBOT
polar acorn
naive pawn
polar acorn
#

You'd have GC when the object with reference types gets cleaned up, right?

Although I guess it'd never get cleaned up itself huh

naive pawn
#

that's on the value though, not the variable

unique depot
rare topaz
#

Wsup !

I'm currently into Procedural Generation, here's what I tried.

-> Height Map : That is awesome, but not for caverns like minecraft.
-> Marching Cubes : That works but not really.

Basically I want an open-world like minecraft but without the cubic aspect.
https://github.com/Scrawk/Marching-Cubes I used this Marching Cubes.
and it do what i expect it to do. but there is a space between chunk that i don't know how to solve.
Here's my code : https://paste.mod.gg/oeqifclautmw/0

I am totally new so any advice/suggestion or even fix are welcome !

unique depot
#

But Update is still using some gc alloc while running

naive pawn
polar acorn
naive pawn
#

seems like it doesn't have an overload to fill an array or list, neither does FindObjectsByType

#

but in general you should not have Find* in Update anyways

#

and that's run for every zombie?

polar acorn
#

Or, at all. If you can manage it

naive pawn
#

this should be a static thing

eternal needle
red igloo
unique depot
#

So I commented out the vector3, and it was making about 97% of the gc alloc while running

subtle mirage
polar acorn
naive pawn
# naive pawn this should be a static thing

a static list of ZombieStateMachine that's updated as instances get created or destroyed (or enabled/disabled, depends on how the flow goes)
then PlayerIsNotBeingAttacked checks if any one of them is attacking

or, all this in a manager component, so it can also compute the result for each frame instead of having to do it for each zombie every frame

naive pawn
unique depot
#

if (PlayerIsNotBeingAttacked() ) //&& Vector3.Distance(transform.position, player.transform.position) <= attackDistance)

red igloo
eternal needle
subtle mirage
subtle mirage
red igloo
#

so for this part if playersToSwitch.Contains(player2)) should I remove player2 and add zone.ObjectToFind? I did that and it didnt recognise it

subtle mirage
blissful vessel
#

Hey, quick question; how do people add the comments to their methods so that you can see like a description of it when you call it from another class? Tried to google it but didn't know the right terminology 😬

naive pawn
subtle mirage
acoustic belfry
red igloo
#

like this?

slender nymph
#

pro tip: use TryGetComponent instead of a GetComponent call and a null check. Also it is not necessary to access the gameObject property on a component to call GetComponent, Component implements it as well

subtle mirage
ruby python
#

Hey all, can anyone see where I'm going wrong with this please? Baffling the crap out of me as I've used this same controller a bunch of times before, but this time, no matter what I do, my flying vehicle constantly loses height (It supposed to stay a fixed distance above the ground)

https://hastebin.com/share/eyuledatuh.csharp

red igloo
naive pawn
#

you could also do out SwitchZone zone and let the generic infer

slender nymph
#

yep, or you can make it ever so slightly shorter with if(other.TryGetComponent(out SwitchZone zone))

red igloo
subtle mirage
#

No, you can remove all of the player2 stuff from the Switcher since the reference is going to be on the SwitchZone instead.

#

Another tip, you can leave the list check in there before adding/removing if you want to ensure it's not attempting to add/remove the same object twice.
It shouldn't, but I like to be thorough. I'm not sure what kind of bugs can come out of trigger Enter/Exit

red igloo
#

as for this part if (inSwitchZone && switcherAction.action.WasPerformedThisFrame()) how can I make a debug.log tell me which one I switched to ?

subtle mirage
#

Once that's figured out, you'll be able to use that same reference in the debug log

naive pawn
#

not really a code question?

cinder jay
slender nymph
#

is the player attached to a canvas for some reason?

naive pawn
#

right now you get a worldpoint, treat it as a screenpoint, and convert that into a worldpoint again

cinder jay
naive pawn
#

viewportpoint is what you want, but the origin is in a corner rather than in the center
you can transform that quite easily

naive pawn
cinder jay
#

i'm getting hard

#
cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
#

here

#

what i want

naive pawn
#

that's not the player position, but ok

cinder jay
#

everything works with the cursor

#

and i want the same with the player

naive pawn
#

is your player in a canvas or not

cinder jay
#

yes

naive pawn
#

and you want to turn that into worldspace

cinder jay
#

wait

cinder jay
naive pawn
#

ok, so it's not in screenspace

#

ScreenToWorldPoint won't work

slender nymph
#

if it is not attached to a canvas then its transform.position is already in world space

naive pawn
#

you said the player is in the middle of the screen and you want to get (0,0) based on that fact?

#

is that correct?

naive pawn
#

there's no space that has that behavior, but there is a viewport space that goes from (0,0) in a corner to (1,1) in the opposite corner

#

so you'd have to do WorldToViewportPoint, and you'd get (0.5,0.5)

#

you can transform that result with some math

#

depends on what value you want for the corners ((1,1) or (0.5,0.5))

cinder jay
#

it's all in 2d with orthographic projection on camera

red igloo
cinder jay
naive pawn
#

shouldn't...

#

could you show your current code

cinder jay
#

that's all I do with playerPos

naive pawn
#

...you didn't change your code

#

also, !code

eternal falconBOT
faint frost
#

hii everyone
i am a beginner and while holding a key it does not work i have to press it again and again
except that if i keep pressing A on keyboard to move palyer to left and while holding A if i press D, D key does not work. i have to leave A and then press D so that player can move right

polar acorn
#

You won't be able to input two opposite directions at once

wooden hill
#

You would have to use Input.GetKey instead of Input.GetAxis

naive pawn
#

wait do you expect pressing D to go right even when A is held?

#

i thought you meant it didn't stop

faint frost
faint frost
# naive pawn i thought you meant it didn't stop

i dont meant to stop it or smth
but like while holding a it moves to left but at sam etime if press d it shoudl chagne direction to right
it was doing thiw but idk how it randomly changed and these 2 problems occured

polar acorn
#

So, you are expecting it to read two opposite directions at once, which it can't do

#

Letting go of left to get it to read right is normal

naive pawn
#

but at sam etime if press d it shoudl chagne direction to right
this.. generally isn't the behavior given
if both directions are pressed it usually results in no motion

faint frost
polar acorn
#

That's not how it works

#

It's a virtual joystick

#

You can't input one direction without releasing the other

naive pawn
#

i mean, you can, but you generally don't

faint frost
polar acorn
naive pawn
#

i mean you can emulate that behavior with keys/input

polar acorn
#

Right, but not with GetAxis

#

You'd need to listen to each button separately

naive pawn
#

yeah, i was making a different point, shouldve worded that more clearly

#

that's a lot of .GetComponent

#

cache BallController in a field here, and type SwitchZone.ObjectToAdd as CubeController instead of GameObject

#

for unity Objects, a bool implicit cast is provided that's the same as != null
you could use that instead if it looks cleaner - doesn't make much difference but just presenting the option

red igloo
eternal needle
# red igloo Yeah I think im just going to re do it. a bit messy tbh

saw it before you deleted it, I was also going to say you dont seem to use that playersToSwitch list anywhere. And yea you should rarely be referencing things by GameObject
instead of checking the _camera.Follow, i think it'd make more sense to check the currentTarget because you already have a variable dedicated for this

red igloo
rare topaz
#

Is there a way to convert a terrain to a plane after some modification (like painting or low/raise of terrain) ? please

rare topaz
#

i was about to create a script to do it xD

eternal needle
# red igloo tbh im so confused. I have the base down already I just need to make it so when ...

its hard to imagine how you're going to be using this script. one thing that i dont understand is why you add these objects to a list, unless you can have multiple zones overlapping in random parts. think about it first in terms of gameplay. Which player should it swap to if there are multiple options? What should happen to the old player if anything?
i imagine you might want to just keep track of the current index if going through the list one by one

rare topaz
#

And is there a way to like do a terrain, then i want on each side the terrain height is 1 ?

rare topaz
dense wind
#

where are the other code channels?

rare topaz
dense wind
#

what am I missing

#

oh

#

I have to go to channels

#

this newfangled discord stuff is hard for an old timer like me

polar acorn
wooden hill
dense wind
#

I was just looking for the role that gives it to me

#

didn't realize I had to enable it

wooden hill
#

perhaps roles give it too... idk its a bit annoying 😄
I'd rather have it show all by default

eager elm
#

Any tips on how to implement toggling on/off Debug.Logs() in a script?

polar acorn
#

if (debug) Debug.Log(...)

eager elm
#

I guess. It would still be included in builds though. If I set it to always false in builds it wouldn't cause any performance hits, right?

#

ah I just realized my class is a normal C# script, so I can't toggle in via Inspector

vocal marlin
#

is there any way anyone could help? My code for adding a function to my button doesn't seem to be working properly. Also another problem - this isn't with the code and more just with unity itself - when I try and use my mouse to click the buttons, they don't highlight in any way or do anything when I click them. https://paste.myst.rs/8eu19ohp I believe the culprit line is line 124, also please ignore the 3 or so lines after that I was trying something.

night raptor
eager elm
vocal marlin
#

hmm okay I'll look into that, do you have any advice about the AddListener thing?

eager elm
#

code seems fine, they probably don't do anything because you can't click them. You can check during Playmode if the newly spawned Buttons have an OnClick event added in the inspector

vocal marlin
eager elm
#

I would also recommend to make a class "ChoiceButton" that handles the setup so you don't have to use GetComponent<> a bunch of times

vocal marlin
#

okay, thanks

#

could the invisible thing be something I have inactive in the inspector because that would be weird if so

eager elm
#

You can change the Inspector to debug mode and look at your event system, it should have a field for "Current Focused Game Object" which will be the mouse hover

#

I also just tested it, a buttons' OnClick event in the Inspector won't display any added events.

vocal marlin
#

in the debug mode it just says no game object is current selected so I don't know what's going on

eager elm
#

Do you maybe have more than 1 event system in the scene?

#

and do other buttons work?

vocal marlin
vocal marlin
#

ok that took longer than It shouldve but yes in another new scene I made the button worked normally

#

this was a completely empty scene though

mortal spade
#

is there any way to call OnMouseEnter() from an object outside the collider? i have a holder with about ~70 different colliders and i want to get the info from whichever one you hover over in one instance

#

rather than from 70 instances into the 1 instance

rough granite
sour fulcrum
rough granite
mortal spade
#

im talking script outside of the object getting the call from the object

rough granite
mortal spade
#

like i know it sounds Weird but i dont know how else to achieve what im trying to do

slender nymph
#

KISS: Just use a component with a static event, invoke that event in OnMouseWhatever and pass the desired component from the object that method is being called on

mortal spade
#

does that impact performance?

#

thats the main reason i dont want to do that

slender nymph
#

use the profiler to determine performance impact

slender nymph
mortal spade
#

will find

rough granite
mortal spade
#

actually true that

#

i was just worried cuz its a lot of instances

#

thank you

rough granite
mortal spade
#

my pc would fry 💔

deep minnow
#

Is calling an if statement oncollissionenter with saod script like playercontroller on said if statement, like a gameOver for example static booleon, is that alot faster then finding said player?

rough granite
deep minnow
#

Had to do a Booleon with the .gameOver

#

global ofcourse

dusty whale
#

guys can anyone help with this problem, i would explain it here but its niche as hell and id spend all day trying to explain it and still wouldnt get it across

#

can anyone who knows a thing or 2 join vc or smth

#

its 2d related btw

rough granite
#

does this server* even have a vc

dusty whale
#

idk

#

i only come to this server when im desperate and couldnt find any solution to a problem

#

there isnt

rough granite
dusty whale
#

if u want we can join any vc

dusty whale
#

its a problem while running

#

or execution ig

rough granite
dusty whale
#

i can send the code snippets if itll help

#

one second

rough granite
dusty whale
slender nymph
#

see the bot embed below 👇 !code

eternal falconBOT
dusty whale
#

ok

rough granite
dusty whale
#
using NUnit.Framework;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.SceneManagement;
public class gamemangerscript : MonoBehaviour
{
    public static gamemangerscript instance;
    [SerializeField] public int maxheartcount;
    [HideInInspector] public int heartcount;
    [HideInInspector] public List<GameObject> hearts = new List<GameObject>();
    [HideInInspector] public List<Animator> heartanimators = new List<Animator>();
    [HideInInspector] public heartmanagerscript heartmanager;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
        heartmanager = GetComponent<heartmanagerscript>();
        heartcount = maxheartcount;
    }
    void Start()
    {
        
    }




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

        if (heartcount == 0)
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
    }
}
slender nymph
slender nymph
dusty whale
#

its not letting me send the rest

dusty whale
rough granite
eternal falconBOT
slender nymph
#

use a bin site for large blocks of code like the bot said

dusty whale
#

its too long

deep minnow
#

Chat GPT works aswel for problems like this

dusty whale
#

it gave me solutions that didnt work or were just dumb and executed the same code but in a different way

deep minnow
#

yh does that, sometimes you got to be very specific though since it only reffrences from the internet

dusty whale
#

heres the code

#

basically heres the context

#

im trying to make a basic heart system in a rpg kindof game so the hearts obviously gotta persist through scenes so i made a gamemanger gameobj singleton with dontdestroyonload() and added the hearts prefab to it as children

#

the heart prefabs are named "heart1", "heart2", "heart3" exc hence the list sorting and stuff

#

basically the whole system works fine until the player 'dies' and the scene reloads

#

then it just becomes a mess

#

sometimes it freezes

#

sometimes it tells me that i destroyed the animator component im trying to access?

#

im not even kidding i think i sat here for like 1 and a half hours trying to fix and at least figure out why this is happening

#

i used chatgpt but to no avail

#

kinda at a dead end here if anyone can help with this

deep minnow
#

Not this advanced yet, but I've noticed if you are trying to specifically do something like isDead etc, you should look into that specifically

rough granite
#

i think it would cause your Awake() in heartmanagerscript may be called before the gamemanagerscript Awake() which causes it add data that is planned to be deleted

deep minnow
#

where in your code does it state the Character dies basically

dusty whale
#

the gamemangerscript runs first

#

-100 priority

#

and the heartmanager is default

#

which is 0

deep minnow
#

Sounds like when you "return" it goes through the "start"

rough granite
dusty whale
deep minnow
#

With Return in the code, does it specifically go to the "void Sart()?

dusty whale
#

oh and i forgot to mention that the gamemangerscript and the heartmanagerscipt are both script components of the same gameobj that has the dontdestroyonload thing

deep minnow
#

since you have it in Awake, there's no reffrence to this I think

#

ok so, you need to seperate them somehow

#

with a reffrence

dusty whale
#

separate what

deep minnow
#

When you die right you have return or something, and you have nothing in start, my guess is that when the code gets read as return it doesn't show in the Awake() if that makes sense

deep minnow
#

ahh ok

dusty whale
#

it has an update that constantly checks the players heartcount

#

if the heartcount ever reaches 0 or under it should run

#

which reloads the scene for now

deep minnow
#

Can't you reference this directly?

dusty whale
#

im fairly new to game dev so if theres a better way to do stuff i wont know lol

rough granite
#

unity runs lowest first

dusty whale
#

rn even when im trying to make an effort to make the code organized its still spaghetti

dusty whale
#

the heartmanager is set to 0

rough granite
dusty whale
#

ur good

rough granite
#

use Debug.Log

dusty whale
#

i have istg

#

ive been bashing my head through the wall with it for hours

rough granite
#

well there aint any here

deep minnow
#

Have you tried putting the get componants in the start the ones that when you lose hp etc

#

since return forces the system to get for Start

dusty whale
#

their in awake does it change anything for them to be in start?

deep minnow
#

I believe it does yh

dusty whale
#

doesnt it js wait until everythings instantiated

rough granite
#

also you gotta clear these before you open a new scene with the gameobject saved
[HideInInspector] public List<GameObject> hearts = new List<GameObject>();
[HideInInspector] public List<Animator> heartanimators = new List<Animator>();

deep minnow
#

Awake is basically when the game starts, but Start is where you put the Return value componants into for it to read it again, I think anyways I maby just overlooking etc lol

rough granite
#

i would assume this is then why you get the errors about missing data

deep minnow
#

or that yh

dusty whale
#

i tried .clear() 'ing them before reloading the scene at the death check

#

is that the same or do i need to destroy the gameobjs?

rough granite
rough granite
dusty whale
#

it takes everything from gamemanager

rough granite
#

it has 2 lists

dusty whale
#

no it just assigns the lists that were initiliazed in gamemanger

rough granite
#

those aren't functions those are variables

#

oh wait nvm i can't read 😭

dusty whale
#

its ok lol

rough granite
#

can you show the error logs that display

dusty whale
#

is this what game dev feels like

dusty whale
deep minnow
#

It's problem solving

#

Took me 3 days to come up with a solution about a problem with my code lol

dusty whale
#

its crashing and the game is frozen

rough granite
dusty whale
#

its not crashing crashing where i have to end task

#

but its really really really slow

#

and this is the first time ive ever seen this (is loading) thing

#

im geniuenly baffled a heart system can take this much time to do

deep minnow
rough granite
dusty whale
#

theres nothing

#

its empty

rough granite
dusty whale
#

yes ik

#

thats what happens when i die

#

it loads and goes into a crashlike state

#

and doesnt show anything in the console

rough granite
#

does the gamemanager object have alot of objects in it?

dusty whale
#

it has js the three heart objs

rough granite
#

and wait whats the point of making it not destroy on load when you destroy it when it loads?
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}

dusty whale
dusty whale
#

or there being more than one instance

rough granite
#

but it'd delete it

dusty whale
#

im pretty sure

dusty whale
rough granite
#

cause when you load the instance the second time wont be null so the else passes and delete this object

dusty whale
#

but then wont there be 2 gamemangers?

#

thatll mess things up cuz theres 2 instances now

#

2 seperate blocks of data i think

rough granite
#

which is why you should make it not be MonoBehaviour and instead have a different script call the load scene

#

having it not be MonoBehaviour means you can't make it a component on an object which limits it to one by default

dusty whale
#

so a scriptable object?

#

how would that work

rough granite
#

well you could just have it be nothing but yeah

rough granite
# dusty whale how would that work

well it just sits there and can be referenced by anything without having reference a component in the scene instead you just call gamemangerscript. whatever variable here

dusty whale
#

but i want to like be able to keep info between scenes

rough granite
#

it will always keep the data through scenes no need for a DontDestroyOnLoad

dusty whale
#

how would that work without a dontdestroyonload

dusty whale
#

how do i set it up

rough granite
#

just remove the MonoBehaviour and Awake, Start, Update functions

#

and put
heartmanager = GetComponent<heartmanagerscript>();
heartcount = maxheartcount;
into their own function thats called through heartmanagerscript first

dusty whale
#

and itll js hold info?

rough granite
#

yeah in memory

dusty whale
#

does it need to still be a gameobj?

#

cuz the script is still attached to a gameobj

rough granite
#

only caveat is everything will need the static tag

#

to keep data persist

rough granite
#

the heartmanager though yeah

dusty whale
#

i dont really get it

rough granite
#

here give me a minute

dusty whale
#

so does it stay as a script .cs file in the project folder?

rough granite
#

yeah

dusty whale
#

and if i set every variable in there to a static tag i can js access it whenver i want to and itll persist through scenes and stuff?

dusty whale
#

i see

#

ill try it

#

thanks

deep minnow
#

yh Tags are quite helpful with this

rough granite
#

though you might need to tweak it a bit since i dont have access to your project

dusty whale
#

i get it

#

basically ur just using it as a medium for carrying info for your game

#

thats actually perfect

#

thanks for the help

rough granite
#

only problem is you wont be able to see the variables in the inspector so you'll need to set them in code for the heart count

queen adder
#

Anybody know what the point of “lists” are??????? What makes them different from arrays and how I use them every time I use mine it gives me an error I just don’t understand what I’m doing wrong

rough granite
queen adder
#

So like you mean an array has 3 and can only be minus and lists can be at 5 but go up?

#

Like “randomlist.Add(1)”

rough granite
#

yeah where when you declare an array it's fixed at the size but a list cause have more data points added to it

queen adder
#

Ohhhhhhhhh wait so like a list you can set it to 1 but then you can add 3 BUT if you do it with an array it can’t it’s only a fixed number?

rough granite
queen adder
#

The video I watched on it didn’t say that

#

I didn’t understand the video I watched he didn’t give good examples

rough granite
#

but yeah

queen adder
#

Ok thx for clearing that up

#

Now I understand 😄

#

How have u been coding for?

rough granite
#

started in september

queen adder
#

DAMN

#

So like a year????

rough granite
#

just under but yeah

queen adder
#

Ok that makes sense why u prob know stuff

#

I started 2 weeks ago 😦

#

😦

#

Why it not let me

rough granite
#

could you send a photo of what you are trying to do?

queen adder
#

Oh im not on unity rn i was asking the question because im sitting in my bed watching videos to understand new concepts

rough granite
queen adder
#

True

#

I think I’m decent though I can do functions and if statements

#

And variables and logic

#

I’m able to code a sword swing script

#

And a sword purchase script

#

🙂

tribal sorrel
#

nvm this post xD

sour fulcrum
tribal sorrel
sour fulcrum
#

You are correct in that it will be controversial outside of that area

tribal sorrel
#

I can see why, but for me it was a great tutor for now regarding very small things 😛

frigid sequoia
#

This is kinda of a generic doubt but like, can I just have like several classes on a single script? Like how does that even work when assigning it as a component? Would it just act as all classes on the script? It's the name of the script just the name of the top class by default but I can have all I see fit?

sour fulcrum
#

You can’t with unity objects (monos and so’s) (unless they are abstract since they won’t show up anyway)

#

You can with others (base classes, structs, interfaces etc.)

frigid sequoia
#

So if I have like a support class that it's not meant to be used alone as mono I should just place it on the same script, but for everything else I should be using a new one right?

timber tide
#

Up to you. If it's only ever used for a specific class then you can even make it an inner/nested class

frigid sequoia
#

So basically I wanna do a Serilizable class which sole purpose its to map a gear slot to a gear type and make it seriazable so I can edit it inside of a list in the editor

#

I am guessing those kind of stuff go inside the script as a new class

timber tide
#

You can serialize nested classes too but there's usually some limit to the depth

#

more of a limitation of Unity's inspector

#

but if you want to make a bunch of serializable classes that are just data containers, you can make like a single script and throw them all into it if you prefer that method

#

otherwise SOs are an alternative if you don't mind asset bloat

frigid sequoia
#

I do mind asset bloat, precisely for that I am asking if I can avoid making more and more script assets lol

frigid sequoia
nimble apex
#
private Dictionary<string, object> publicData { get; set; } = new();

public T GetPublicData<T>(PlayerDataConstant.PublicDataType type) => (T)Convert.ChangeType(publicData[type.ToString()], typeof(T));```

someone told me if i use pattern matching on this function it would be faster/better , but how?
#

the dictionary must be in the form of <string,object> due to API restriction

bright zodiac
#

you asked about perf but that particular Convert.ChangeType is actually slow

#

how many types will be in the dictionary? Does a simple switch-case wouldn't do the job here

#

also you may want to try-catch there

nimble apex
nimble apex
#
foreach (var(key,item) in await CloudSaveService.Instance.Data.Player.LoadAsync(PlayerDataConstant.PublicKeys))
{
    publicData[key] = publicData[key] switch
    {
        PlayerDataConstant.PublicDataType.UserID => item.Value.GetAs<Int64>(),

        PlayerDataConstant.PublicDataType.Lv => item.Value.GetAs<byte>(),

        _ => throw new Exception("retrieved data failed to convert! ")
    };
}```
#

this should be better, plus this function only called once after player login successfully

#

IT WORKED 😭

faint frost
buoyant plank
#

Devs lääh ❤️

burnt stirrup
#

hey can anyone help me set up a basic third person player controller with cinemachine?

#

a lot of tutorials with cinemachine are very old and the ui has been changed so i cant really do much

ivory bobcat
faint frost
atomic prairie
#

hi guys, can i ask why my sprite is so low quality and compressed in the image

hardy maple
atomic prairie
#

ah okay i think i got it

#

i did that and also changed the compression thing on the side to none

#

which shoulda been kinda obvious in hindsight

frail hawk
#

and make sure to import your sprites in a normed size like 256x256 / 512x512

atomic prairie
#

also im not sure if i just imported it in wrong or what

#

i just dragged it in from the file explorer instead of doing right click import new asset

frail hawk
#

that doesnt matter but the size is very important for the compression

atomic prairie
#

ah okay

#

thanks!

grand snow
worthy tundra
#

when i build the game im getting "cannot create FMOD" error

#

i dont get it in the editor

frail hawk
#

have you tried to google it?

worthy tundra
#

very few results

frail hawk
#

i found quiet a few tbh, seems to be something obvious

ashen cliff
#

hey guys im really new to programming and unity. can anyone give me some advice on the best way to learn c# via unity?

slender nymph
#

there are beginner c# courses pinned in this channel, then the junior programmer pathway on the unity !learn site is a good next step to learn how to use c# inside of unity
I personally recommend learning c# separately first because you will then have an easier time learning to use the engine since you'll already understand the basics of the language

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ashen cliff
#

on avg how much does it take someone to become a junior level game dev?

#

like from scratch

#

sorry for my bad english

worthy tundra
keen sand
#

hey i want help

rich ice
eternal falconBOT
keen sand
#

i learn't basic c# from the brackeys c# basics series but i still don't know how to code as in i can not code in unity but i cant tell what he is do ing but i don't know how to code myself

vocal marlin
#

hey does anyone know how to get vscode to detect unity errors and such, i'm returning to a project after a long while and vscode has just decided to be annoying

keen sand
#

i can only do it useing the .NET frame work

eternal falconBOT
vocal marlin
keen sand
#

does any one know how i can learn how to acually use c# in unity

slender nymph
eternal falconBOT
#

:teacher: Unity Learn ↗

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

keen sand
#

ok thnx

#

i will check them out

slender nymph
#

it is much easier to learn c# separately from unity because you'll get an understanding of how the language works without also needing to try and learn how the engine works at the same time

worthy tundra
#

what is an FMOD

#

i never used it but unity is giving me errors about it

slender nymph
#

what is the actual error

worthy tundra
#

previous builds were find

#

fine

#

but now it gives me this

slender nymph
#

and have you googled the error? the first result gets some pretty useful information

slender nymph
#

great! then consider reading that information

worthy tundra
#

but the only ones i found were the error is in builds are 0 answers stack overflow threatds

slender nymph
#

and if you need further help then see #854851968446365696 for what to include when asking for help

vocal marlin
# eternal falcon

I had already done everything that was stated here and the problem persists so idk what else to do

eager elm
slender nymph
#

there is also an asset for more of FMOD's functionality in the project though

worthy tundra
#

bruh i found like 7 different threads for that problem and not 1 has an answer