#💻┃code-beginner

1 messages · Page 667 of 1

keen dew
#

Yes but I'm pretty sure that's not what you actually want

thick spoke
#

k i see

naive pawn
#

though gotta be a bit more precise - the actual classes inside each other, or class instances?

cosmic dagger
#

Okay, but having your "OOP script filled with classes and all good" doesn't tell us anything. It's best to give an example . . .

red ravine
thick spoke
naive pawn
#

the actual class definitions or class instances

#

it seems like you don't understand these OOP terms?

keen dew
thick spoke
cosmic dagger
#

I would just start coding to have something physical that we can look at and reference . . .

naive pawn
thick spoke
cosmic dagger
#

It's confusing because everything mentioned is hypothetical (and complicated for anyone to grasp) . . .

thick spoke
keen dew
thick spoke
full kite
#

so basically, on the one that on the build is the same as on the editor i got 60 fps capped 12 ms and the other one that on the editor is 10 times slower i got 800 fps 1 ms. But if i remove time.deltaTime i go like a supersonic

#

What should be put instead of time.deltaTime

#

And what did I do to unlock it from 60 fps to 800 fps, since I got this problem

keen dew
#

You don't put anything instead of it, you change the sensitivity value to something much smaller to compensate

full kite
#

!code

eternal falconBOT
full kite
keen dew
#

It depends on the use case

full kite
# keen dew It depends on the use case

Lets troubleshoot a bit because i dont get a thing. I have 800 fps in the game editor but in the game only 60fps. I builded the game like 10 minutes ago and I had 2000 fps in the builded version, but now after starting another project, builded that, now on this project the build version stays at 60fps. How can I change that and why does it change automatically.

#

Like how to cap the fps or how to uncap the fps

keen dew
#

The settings related to that are vsync and target frame rate. Look up how to set or unset those

full kite
#

Now it doesnt even move in the build when its 60 fps and on the game editor, its moving perfectly fine.

naive pawn
cerulean vapor
#

so i'm trying to make producer1 make points and producer2 make producer1 but when i tried to make the incomePerInterval increase with the Prod1nr but it just took the points and stopped making points passively

brazen crescent
#

From a quick glance I saw you have a function within a function, you have void UpdateButtonText() function isnde your Void Clicked(). You should separate the two functions

cerulean vapor
#

didn't even see that

#

but it seems to have broken more things

#

now it shows me it passively make points but doesn't make it and now the interval stopped working entirely

frigid sequoia
#

Hard to tell when we don't have the context on how the PassiveIncome works

frigid sequoia
cerulean vapor
#

oh i've fixed it already

#

but now i have this error

slender nymph
#

warnings are not errors. and that warning is pretty self-explanatory

cerulean vapor
#

ohh

#

i see now

#

it's this one but i already have Addpoints to public

slender nymph
#

have you actually saved the code? also stop sending screenshots of code. see the bot message below for how to correctly share your !code 👇

eternal falconBOT
thick spoke
#

btw can some explain what is time.deltatime?

slender nymph
#

that's literally all it is

naive pawn
thick spoke
#

ah i see, thanks @slender nymph

thick spoke
still wren
#

is this smart

steel smelt
naive pawn
#

depends on what you mean by "smart", but there's no real issue with it i guess?

rich adder
still wren
#

thanks

still wren
#

i meant if this is how th e professionals do it

rich adder
#

Action is a type of delegate too btw (no args / is void return type)

still wren
#

thankyou nav

grand snow
thorn holly
#

sorry i just got around to implementing this but just realized..what am i supposed to attatch the monobehaviour to?

rich adder
thorn holly
#

yeah i just dont fully understand they're code yet

#

like for example a monobehaviour has to be attatched to something but when its just in my inventory its not like theres a prefab of the item so what am i attatching it to?

rich adder
#

not sure the exact context so cannot say, you'd have to explain abit more what you're doing

thorn holly
#

im making an items system for my game and they reccomended doing it like they're code up there, i just dont understand whats going on

#

idk i just cant comprehend how im supposed to do this

#

like the structure

rich adder
thorn holly
rich adder
#

I would suggest you start small, and build your system up that way

thorn holly
#

im trying and ive run into a roadblock

rich adder
#

its easier to learn from your own mistakes and find out where the pitfalls are

thorn holly
eternal needle
#

you really dont need to set it up the way you were shown there

#

in what way do you need static for your item system?

thorn holly
#

idk i thought i did but maybe i dont

#

hang on

#

i dont know

#

nvm

eternal needle
#

i meant more like, what value are you using it for?

thorn holly
#

just dont mind that lets start from the beginning

#

im just completely lost on the overall structure of how to set up the item system

#

like what should each item be? a scriptable object? monobehaviour script? prefab?

#

i cant figure out how to make it work

rich adder
#

follow the KISS principle 😄

eternal needle
#

dont worry about the code yet. the first thing you should do then is think about what you want items to actually do. To you, what is an item system? what does the user see, how do they interact with it?

ashen ferry
#

anyone ever ran into this bug where something like float just sets itself to 0 magically, my third field does that rn if I swap places it with something then whoever is third still resets even with 0 refs to it and not serialized lmao I actually remember getting this like year ago so im gonna ask again anyone know what im talking about and did you solve it?

polar acorn
thorn holly
polar acorn
#

You could make the variable private and see what throws an error

ashen ferry
polar acorn
#

or turn it into a property and breakpoint on the set

thorn holly
rich adder
#

done such a system before including recipes and works great with SO

thorn holly
rich adder
thorn holly
#

poco?

rich adder
#

plain c# object (like class)
(Plain Old C#/CLR Object)

thorn holly
#

thats what i was doing

ashen ferry
thorn holly
#

so then do i make it so for each item i make a new SO of the base item SO and a new subclass of the base item poco?

polar acorn
#

The inspector takes priority

ashen ferry
#

tried without attribute after filming

#

also you can see in rider "unchanged" or whatever value it is

#

if I set it in inspector

thorn holly
eternal needle
# thorn holly pretty muck exactly like minecraft - they can store it in their inventory, use i...

ok so you want items that can be used and every item presumably can be dropped. items will be used in different ways, so that means you'll need inheritance to define the Use functions in derived classes. Your base item class right now seemingly just needs an abstract Use method and possibly a virtual Drop method if theres a chance a deriving class could change its behaviour
A scriptable object is simply used as a data container. You would use it to store values and pass it to your objects. Your items would likely be represented as monobehaviours in the end.

eternal needle
thorn holly
#

i made an inventory system, slot system, etc

#

next step is making it so actual items are passed around that inventory and slot system

eternal needle
#

slot system as in UI?

#

maybe just show what you already have then

thorn holly
polar acorn
thorn holly
# eternal needle maybe just show what you already have then
eternal needle
# thorn holly yes sorry

you really shouldnt worry about the UI either yet imo. That should come way later. Anyways the UI is just a matter of slapping a sprite in your scriptable object, then reading that when needed

thorn holly
#

that wouldnt be a huge deal

naive pawn
#

you don't have to delete everything

#

what i usually do when i have to remake a system is rename the folder for that system with an extra underscore, and then create a new folder for the new version
then you can copy over stuff that doesn't need to be remade, or see your previous code for reference if needed

#

remaking a system doesn't have to involve throwing out all the work you did

#

and you can also delete stuff you've already recreated to see what you have left to remake

thorn holly
#

for example, how do i give the poco a reference to its so if i cant serialize base c# scripts?

naive pawn
#

oh uh, i just got here. idk if you have to remake or anything like that, i haven't been following 😅

#

i just mean if you have to remake, you don't have to delete the entire thing all at once and start over from scratch

eternal needle
rich adder
#

the SO just defines what type of item it is

#

poco doesnt care about the SO itself

thorn holly
rich adder
#

Feed the stats from POCO and SO to the gameobject (another main script) then deal with the logic there and other things like moving it around or creating new ones

eternal needle
#

the first major thing i notice is that your UI stuff is intertwined in your inventory. you'd probably want to reconsider that. if we're comparing this to a minecraft inventory, well npc's can have items too. They dont have a UI. Then your inventory doesn't really have anything in regards to using items.
your item class also doesn't have a method for dropping. It should likely reference a prefab from the ItemSO to be dropped so you have a visual model on the ground.
The ItemSO doesn't make much sense for why you need a reference to the player, or why its static. that 100% should be removed in any case.

rich adder
#

for example. Different game type but same concept/idea.. If I have a Card prefab, it just needs to create itself from stats in an SO and Poco, then anything modified (the copied POCO stats) is on that specific Card instance

thorn holly
#

this is getting too confusing ill prolly remake it

rich adder
#

In a "minecraft" style.. Imagine SO is saying "this is wood"
Poco is "we copy base Durability of 10" to put on our actual Item gameobject , then we can -- Durability on the copy of poco stats

#

the gameobject is the glue that holds those together, the tangible object you can move around copy/modify stats from, interact in the game world etc.

eternal needle
#

still i dont see why we're worrying about the SO when the item class right now has 2 fields and 1 out of 2 methods they want.
The first thing you should do is make your foundation. An item class that can be used or drop items. It doesnt matter right now if the use or drop does anything. Put debug logs in there that say "dropped from game object name".
Make a collection that holds your Items and have a way to Use or Drop each item. none of this should involve UI yet

thorn holly
#

wait rewind

#

so items are a poco?

#

cause nav says it should be a monobehavoiur

#

or a gameobject?

#

idk i dont understand

rich adder
#

Item could be a MB if you want it to

#

MB just makes it easier for example doing Pickups and stuff in the game world

thorn holly
#

i was thinking every item is its owned selfed contained, nonmonobehaviour, non game object, etc, just a so or poco or something

eternal needle
#

its up to you if you want to make it a poco. i think it makes sense to do. When dropping an item, you would just spawn a prefab.

thorn holly
#

then for example for dropping stuff, i just make a generic dropped item prefab that takes in one of these self contained item things and then displays, its icon

thorn holly
#

thats what im trying to do in my code

#

the player ref is spaghetti code ill delete that

rich adder
#

the problem with that IMO is you have to spawn a gameobject everytime you drop something

#

instead of just hiding one you already have in inventory

thorn holly
thorn holly
rich adder
#

it ultimately comes down for whats easier for you
if you think one way is easier to work with use that

thorn holly
#

for example should every item in a stack have its own gameobject?

thorn holly
rich adder
#

thats why i just store the gameobject already instanced and hide the gameobject, but thats Easier for me, it may not for someone else

eternal needle
rich adder
thorn holly
eternal needle
#

the dropped item will usually have a collider and fall until it hits the ground, might spin around, might be smaller, etc etc. none of this logic needs to be on the object held by the player

thorn holly
#

ok idk why were still debating this id like to go with bawsi's structure if thats ok

#

it makes more sense to me

eternal needle
thorn holly
#

right?

rich adder
thorn holly
#

like i can sorta see where ur coming from but even an individual player and an npc would have very diff types of inventories

eternal needle
thorn holly
#

this inventory prefab i created is for chests and the player

thorn holly
#

(i think thats the proper term)

eternal needle
#

its not a layer of abstraction. your inventory is not different from players to npcs, or even chests. An inventory is an array/list of items, that's all. there is no different type of inventory here
This would be like if you had a class called EnemyHealth and PlayerHealth.

#

the UI should be separate entirely because its only for your user. this is why you also make it last because it's going to be interacting directly with your inventory

rich adder
#

yes UI is def not something you should even have in your mind right now..

#

and if you designed it around UI at all, go back and redo that

hallow sun
#

Anyone knows why this aint working? I already have another working event but this one doesnt work for some reason, names are all correct idk what the problem might be.

public class Scoreboard : MonoBehaviour
{
    public Text txtScore;
    int score = 0;

    void OnEnable()
    {
        GameEvents.current.score += SetScore; //error here: object ref not set to an instance of an object
    }

    void OnDisable()
    {
        GameEvents.current.score -= SetScore;
    }

    void SetScore(int points)
    {
        score += points;
        txtScore.text = score.ToString();
    }
}
#

Here is GameEvents

public class GameEvents : MonoBehaviour
{
    public static GameEvents current;

    private void Awake()
    {
        current = this;
    }

    public event Action<int, Vector2, Color> vfx;
    public void SpawnVFX(int id, Vector2 pos, Color color)
    {
        if (vfx != null) vfx(id, pos, color);
    }

    public event Action<int> score;
    public void EditScore(int points)
    {
        if (score != null) score(points);
    }
}```
rich adder
hallow sun
#

SpawnVFX works fine though...

thorn holly
#

ill post the code as i go to ensure im doing it right

#

if thats ok

hallow sun
#

i guess i can put it in a coroutine to wait a second

rich adder
rich adder
hallow sun
rich adder
#

you already using a singleton lol

#

I just suggested you change the order of execution for it so you dont have to do some hacky shit like delay 1 second..

hallow sun
#

yeah but i just got that from a tutorial

rich adder
#

make the singleton run slightly before anything else that needs to reference them

hallow sun
#

yup this works better 👍 thanks

thorn holly
#
#

@eternal needle is this what you mean?

brave robin
#

Quick question: what does POCO stand for? 🙂

naive pawn
#

plain ol' C# object

rich adder
#

really something you could google lol

brave robin
#

Ahh, thanks

naive pawn
#

the C may change and may stand for other things

brave robin
naive pawn
#

POJO is a related term for the same concept in different languages

rich adder
#

original from java iirc

#

C was CLR object

naive pawn
eternal needle
thorn holly
eternal needle
thorn holly
#

kinda like navs idea

#

so like

class ItemDatabase : MonoBehaviour{
  [SerializeField]
  private AppleSO appleSO;

  public Apple ConstructApple(){
    return new Apple(appleSO);
  }
}
#

that might be kinda overkill since every item would need a construction method but you get the point

eternal needle
#

you might end up having an item database anyways because of needing to save inventories based on ID. Im not so sure how you'd want to handle spawning different items because it depends really how they're spawned

floral wren
#

And a list of SO which you can all call the same function "Create".

thorn holly
thorn holly
#

or like define it when i make a new type of that so

#

if that makes sens

brave robin
#

You could make the SO abstract, if you don't have too many variations of it

eternal needle
thorn holly
eternal needle
thorn holly
#

isnt the whole point of scriptable objects to make one template and use it multiple times?

brave robin
#

Can the Create method in the SO find out what it needs to know from the fields in the SO? Or does it absolutely need specific code that will change for every kind you make?

thorn holly
#

ohhh wait i get it

#

i mean i could do a name based thing

eternal needle
thorn holly
eternal needle
#

from how i see it, you'd be creating a new SO class everytime you have to make a new Item class, which would only be when you need different fields or different use/drop functionality

thorn holly
eternal needle
#

so yea maybe food could be one class

thorn holly
#

and then stuff with functionality thats too special to generalize can just have its own so

#

and its own item class

eternal needle
#

yea sounds about right. i suspect you'll have quite a few item and SO classes that just have one item "template" associated with it but that really isnt an issue. its just game design

#

in the minecraft example at least, each tool (shovel, pickaxe, etc) would have a few different SO assets because of the different types like wooden, iron, diamond

agile helm
#

Hello there

thorn holly
#

so every item has the base item so instance with basic info all items need

#

but food items also have a reference to a food so with info on how much it heals

#

ok ill figure this out

#

Tysm for everyone’s help

thorn holly
final trellis
#

how can i have my own methods have something similar to this? ( the method description )

polar acorn
#

<@&502884371011731486>

#

99% chance of malware

fickle plume
#

bot missed it 👍

hallow rock
#

Possible chance to fix this?

polar acorn
hallow rock
hallow rock
#

yellow

#

basically

fallow jewel
#

Hey is their any unity prodigys in here looking for help

hallow rock
#

the yellow ones disable me from testing playing

polar acorn
#

the compile error does

hallow rock
#

how can it be fixed.

polar acorn
#

Look at the line the error is on, and fix the syntax

fallow jewel
#

I just want a scroll view to show some images on a menu via a script and its annoying me i asked ai no solution was found

polar acorn
#

should be underlined in red

#

dead simple

polar acorn
#

It'll position them automatically as new ones are added

fallow jewel
#

Yes that part is working but i was trying to make a script to just throw a ton of images in their

polar acorn
#

So spawn a ton of Image objects

fallow jewel
#

Like i select them in a unity script like a image and it just throws them in

#

How would i do that im not very good at coding

polar acorn
#

Make a list of Sprites, loop over it, and for each one spawn an Image prefab and set its sprite to that one

fallow jewel
#

I was using this and it wasnt doing anything so i scrapped most of it to retry

rich adder
fallow jewel
#

Ye im being quick while highlighting it my other account on my pc is seperate because ive been tokenlogged and it was horrible

#

And ifs just awkward to send one to my phone in rapid speed

rich adder
#

2025 there should be no reason take a photo of what a screenshot can solve

fallow jewel
#

Just trying to get some quick revive help for a silly project to pass my course

polar acorn
#

So, you have a list of sprites. That's the first step of what I suggested

rich adder
fallow jewel
#

They tought us barely any unity gave us the thing and said play along with it and figure it out college was such a awful idea

#

And then handed us this giant assignment to make a detailed idle game for a phone

rich adder
#

do you at least know how to setup the code? like loops and instantiate stuff ?

fallow jewel
#

Little bits i have been using ai to learn and help me through confusion and guide my steps

#

Even if it is controversial it can be a good learning help

#

Its just a learning agent for me once i learn my way and get it burned into my brain i can move it away

cinder ingot
#

Are you using it to write your code?

fallow jewel
#

Im trying to rely on it as little as possible

rich adder
fallow jewel
#

Guiding my way if i need to use it

#

Having it breakdown to me what stuff does in coding lol

#

Havent used C#

#

Before we have done bits of python and scratch at college its embarassing

cinder ingot
#

Well someone has already given you the answer on how to accomplish your task. I would, if I was you, write that solution in commented form then go about accomplishing it one step at a time.

rich adder
#

scratch can be very useful..especially teaching breaking down ideas into coding logic

fallow jewel
#

I appreciate the help i also assume it would be possible to only make the images appear under a logic if so and so is collected

cinder ingot
#

Its going to be near impossible for us to help you code if you don't even know how to code to begin with...

#

No intention of being rude, or question your experience, but were not going to copy paste code for you.

rich adder
fallow jewel
#

I would just like to if its possibe in unity to make something from a scroll view to do thay

#

That

#

Im not asking for you to write me the code

cinder ingot
#

If you're in a college program, I suggest reaching out to your professor and asking for some guidance. If its supposed to be done via coding in C# than you should have a companion course teaching C#, otherwise the method to solve your issue is probably achievable another way.

fallow jewel
#

Unfortunately he is useless ill have to reach out to my older friend who codes for fun to see if he can assist in my trouble Thanks 😅

cinder ingot
#

You really should get some guidance, because if you're expected to do a C# assignment with no courses or direction, than you're not really learning anything.

violet lodge
#

Hello, I'm doing my very first project and my character just falls into the void. I want him to not have gravity affect him at all as I'm doing an orthographic thing. I have some script for its movement that my teacher sent (I cannot ask them for help they do not answer) and every time I press the assigned movement keys this error appears (There's also pictures of my character made into a prefab, the input manager, and my script):

slender nymph
#

holy color scheme batman

#

you need to get your !IDE configured because you have a bunch of issues. also that color scheme is god awful

rich adder
#

bro is in the matrix

eternal falconBOT
violet lodge
rich adder
slender nymph
#

having configured tools is a requirement to get help here, so do that first

violet lodge
rich adder
#

the code editor , its an IDE

#

where you type code into

violet lodge
#

so like visual studio?

naive pawn
#

-# fyi nav you can shift+click reactions so the menu doesn't go away

violet lodge
#

ok, how do I get visual studio configured? At the very start it asked me to install a unity developer package and I did, what else should I do?

rich adder
rich adder
copper jasper
#

Why does my camera bob go crazy when i look up and when i land it glitches

    void CameraBob(float Speed)
    {
        if (!isGrounded) return;
        if (moveDirection.magnitude <= 0) return;
        if (Vector3.Dot(moveDirection.normalized, camTransform.forward.normalized) < 0.99f) Speed /= 2;

        headBobTimer += Time.deltaTime * (Speed / 2);

        float bobPos = originalCamYPos + Mathf.Sin(headBobTimer) * (2/ Speed);

        camTransform.localPosition = new Vector3(0f, bobPos, 0f);
    }
violet lodge
slender nymph
#

we can see that it isn't depsite your god awful color scheme

rich adder
polar acorn
violet lodge
#

the preferences I mean

violet lodge
violet lodge
rich adder
polar acorn
eternal falconBOT
violet lodge
rich adder
#

esp the Regenerate part

fast fern
rich adder
#

You can use Image component on UI then set it to Fill mode and control value via code (the value here is 0-1 so you would currentVal/max )

#

the value is very basic stuff in Update using += deltaTime * increaseSpeed etc.

fast fern
#

I'll try

#

I've been struggling with this bit

rich adder
#

its a pretty basic mechanic

fast fern
#

Is there anything I could read/watch?

rich adder
#

idk any specific video

#

something like

if(KeyHeld && someValue < maxValue)
someValue += Time.deltaTime * increaseSpeed```
You probably dont need the keyheld if its just controlled byitself to hit it at specific time
fast fern
#

Also what do we call these? Time event bars?

copper jasper
#

Why does my camera bob go crazy when i look up and when i land it glitches

    void CameraBob(float Speed)
    {
        if (!isGrounded) return;
        if (moveDirection.magnitude <= 0) return;
        if (Vector3.Dot(moveDirection.normalized, camTransform.forward.normalized) < 0.99f) Speed /= 2;

        headBobTimer += Time.deltaTime * (Speed / 2);

        float bobPos = originalCamYPos + Mathf.Sin(headBobTimer) * (2/ Speed);

        camTransform.localPosition = new Vector3(0f, bobPos, 0f);
    }
rich adder
#

be patient if someone knows the answer they answer , no need to post it again right away..

copper jasper
#

its cause theres alot of messages now so i wanted people to see

#

cause it got hidden in a way

rich adder
#

its not that bad..people still do have scrollbars

copper jasper
#

idk i just wanna fix this and sleep 😭 its 12 am

rich adder
#

start by debugging your issue instead of just throwing hands up and hoping someone has answer right away

copper jasper
#

ive been trying

rich adder
copper jasper
#

i started coding yesterday btw 😭

rich adder
#

you have plenty of time ahead of you, its easy to burn out like this

copper jasper
#

I spent my whole 2 days trying to fix screen tearing due to 1 settings 💀 I was so annoyed that i lost 2 days js cause of that

rich adder
#

there is some values you could debug and see why they are different at specific times

copper jasper
#

whats sin

#

Mathf.Sin

#

never really understood it

rich adder
copper jasper
#

I hate maths 😭

#

does it js remove the sign to get a absolute value

rich adder
#

its part of the job lol

#

you put radians and gives you value between -1 and 1

#

these functions help with giving it some motion

copper jasper
#

Hmm alr ima try fix it tmrw i need mi sleep 😭

#

Gn

polar acorn
copper jasper
#

Ig i have alot to learn 😭

copper jasper
violet lodge
#

what do I do here? step 3 tells me to go to the add button, there is none

tiny bloom
#

How can a client destroy a game object that was instantiated by the host?

hallow rock
violet lodge
#

And also, which one?

acoustic belfry
#

in UNITY2D, how i can make an Object move at a position i want?

for example, we have a Boss, is like an enemy, it has the same enemy programation/script of following the player POS by trying to make their POS into the player POS. but

the Boss inside a function has to Jump, and Slam down, and also, the Boss has to inside another function has to Run a lot o the right, and a lot o the Left. How?

i should use Add-Force or smt?

rich adder
violet lodge
#

this one

rich adder
#

the editor is there, you need to just verify the Unity workload is there in VS Installer.

thorn holly
#

@eternal needle sorry super late but quick question, can i give the Item class a static variable holding the player assigned by a game manager so each item has a ref to the player

frosty hound
#

Just make the player a singleton. But the items needing to know about the player is a red flag.

thorn holly
frosty hound
#

The player eats the apple, so it heals itself based on the apples properties. The apple doesn't know it gets eaten and then tells the thing that ate it what to do.

#

The authority lies on the player to make those decisions.

eternal needle
#

this still doesnt change from before where we said static makes no sense here

thorn holly
teal viper
#

You could check the type of the character. If it's an NPC do nothing. If it's a player character, call the desired method.

#

If npcs don't have hunger, don't implement the hunger stat and methods in them.
Ideally, you'd have some kind of Stats system where you can dynamically add or remove stats from characters.

#

Then when an item is supposed to restore some stat you check your stats collection, and if the stats is not there you just ignore the effect.

thorn holly
#

so maybe like a self contained stats monobehaviour

#

so a base stat monobehaviour with like a value, add, and remove method

teal viper
#

I'd make it a plain class, but it depends on your project I guess.

thorn holly
#

like a monobehaviour component with a list of stats that i can add to?

teal viper
thorn holly
teal viper
#

It's neater and easier to extend. You can have hundreds of different stats this way. Imagine having hundreds of component on a go.

thorn holly
#

or maybe theres a way to serialize it?

#

so that each one can have the same component

sour fulcrum
thorn holly
#

like make it so that theres a monobehaviour with an array of type stat so that i can drag in the base c# stat scripts from the inspector

#

i just realized that naming was confusing

sour fulcrum
#

1 thing im gonna nitpick because a lot of people do it, the word instance and class aren't interchangable with script, you'd never be dragging scripts anywhere

with base classes, you can't really drag and drop them like that. for various potentially good or dumb reasons Unity isn't the best when dealing with base clases in the editor

thorn holly
#

oh i was hoping that it would automatically instance it

sour fulcrum
#

you can serialize them in the editor in general though, by putting [System.Serializable] on the base class itself

#

and usually you want to use [SerializeReference] on the field that's storing the instance of the base class

thorn holly
#

so say my poco is the class Stat, I would put [System.Serializable] in the poco and then in the monobehaviour component attatched to each entity I would put a [SerializeReference] Stat[] stats then drag the Stat subclasses into the stats var?

sour fulcrum
#

So this is the bad part about base classes and unity editor stuff

#

you can do all of that except for that last part

#

you can't drag base classes in any context

#

and you can't select what type they are

#

if you have Stat[] stats it will show you an array of stats that you can add and remove from

#

but you can't say like oh this one is gonna be this inherited version of Stat

#

there's no type picking

thorn holly
#

so what should I do?

sour fulcrum
#

Couple different ways people go about it.

There's quite a few third party solutions that introduce ways to type pick base clases like that on github, asset store etc.

There's also some solutions that can be made where you basically have a scriptableobject per stat type and that scriptableobject has a function that can create and return said type, and you use a asset of that SO to drag and drop, create them etc. . this solution works abit better if your comfortable with generics

thorn holly
#

this feels a bit excessive

#

realistically an npc is never gonna use an item

#

and realisitcally nothing other than the player is gonna have a stat other than health

sour fulcrum
#

At the end of the day no one here can force you to pick a solution, You know your project more than anyone and can choose what route to take it. Ideally responses here just help you make a more educated description 😄

thorn holly
#

I get that but also it just kinda feels like whenever I ask a question instead of answering it, people say “actually you should do it like this” and then just dip so it takes forever to figure out what they actually mean

#

Like it’s already been an hour and 40 minutes and I feel like I still don’t have a concrete solution nor an answer to my original question

thorn holly
thorn holly
#

No

#

At least in terms of inventory it’d be more like Minecraft

sour fulcrum
gray anchor
#

Hello there! I am just trying to put some code in for a Health UI/Hearts, while following a Tutorial. I got the little Heart Meter in (3 Hearts total) but for some reason it only takes 1 damage, and only to the middle heart.

thorn holly
teal viper
gray anchor
# teal viper How are you investigating/debugging the issue?

I was just trying to compare the code I made to the code in the tutorial, and it LOOKS identical, but the results are not. I do know the Tutorial is based in an earlier version of Unity. So I figure it might have to do with that? But I cannot tell.

teal viper
# gray anchor I was just trying to compare the code I made to the code in the tutorial, and it...
  1. If the code is exactly how it is in the tutorial, then it's likely some setup in the editor/inspector/scene missing. Make sure you didn't skip any steps there.
  2. Make sure you don't have errors(and possibly warnings) in your console log.
  3. Learn how to debug issues. Learn about debug logs and visual debugs and how to use them. Log important info where your logic executes to make sure that it does execute and the relevant values are what you expect.
  4. if you need further help, share your !code and a link to the tutorial.
eternal falconBOT
gray anchor
# teal viper 1. If the code is **exactly** how it is in the tutorial, then it's likely some s...
  1. It did not SEEM like I did. I watched this section of the Tutorial ~3 times, checking each time.
  2. No errors, but I did have 2 Messages?
  3. I am definitely interested in this.. but I think I am a little too shitty at this to know where to start heh.
  4. Certainly. I had two different pieces of code this could interact with, and here is the Tutorial Link to the time I am at: https://youtu.be/Pkc4A1ukbJU?t=5224

First Related Code Thing: HealthUI

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

public class HealthUI : MonoBehaviour
{
    public Image heartPrefab;
    public Sprite fullHeartSprite;
    public Sprite emptyHeartSprite;

    private List<Image> hearts = new List<Image>();
    public void SetMaxHearts(int maxHearts)
    {
        foreach(Image heart in hearts)
        {
            Destroy(heart.gameObject);
        }
        hearts.Clear();

        for (int i = 0; i < maxHearts; i++)
        {
            Image newHeart = Instantiate(heartPrefab, transform);
            newHeart.sprite = fullHeartSprite;
            newHeart.color = Color.red;
            hearts.Add(newHeart);
        }
    }

    public void UpdateHearts(int currentHealth)
    {
        for (int i = 0; i < hearts.Count; i++)
        {
            if(i < currentHealth)
            {
                hearts[i].sprite = fullHeartSprite;
                hearts[i].color = Color.red;
            }
            else
            {
                hearts[1].sprite = emptyHeartSprite;
                hearts[1].color = Color.white;
            }
        }
    }
}

By the end of this video, you’ll have everything you need to create an complete 2D platformer game in Unity! 🎮 This tutorial covers all features like character movement, jumping, enemies, collectibles, and more. Perfect for beginners and anyone looking to improve their Unity 2D game development skills!

Whether you’re building your first ...

▶ Play video
gray anchor
# teal viper 1. If the code is **exactly** how it is in the tutorial, then it's likely some s...

Second Related Code Thing: PlayerHealth

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

public class PlayerHealth : MonoBehaviour
{
    public int maxHealth = 3;
    private int currentHealth;

    public HealthUI healthUI;

    private SpriteRenderer spriteRenderer;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        currentHealth = maxHealth;
        healthUI.SetMaxHearts(maxHealth);

        spriteRenderer = GetComponent<SpriteRenderer>(); 
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Enemy enemy = collision.GetComponent<Enemy>();
        if (enemy)
        {
            TakeDamage(enemy.damage);    
        }
    }

    private void TakeDamage(int damage)
    {
        currentHealth -= damage;
        healthUI.UpdateHearts(currentHealth);

        StartCoroutine(FlashRed());

        if(currentHealth <= 0)
        {
            //player dead! -- call game over, animation, etc.
        }
    }

    private IEnumerator FlashRed()
    {
        spriteRenderer.color = Color.red;
        yield return new WaitForSeconds(0.2f);
        spriteRenderer.color = Color.white;
    }
}
teal viper
# gray anchor 1. It did not SEEM like I did. I watched this section of the Tutorial ~3 times, ...
  1. Start from understanding the problem. What does it mean code wise that "the heart meter only takes 1 damage and only in the middle"? Where is the code that should deal the damage? Does it deal the amount of damage you expect? Log it. What code is responsible for modifying the visuals(disabling ui or something?)? Does it execute correctly? Does it apply to the correct objects? Log the relevant values.
gray anchor
teal viper
rich adder
#

nope. The tutorial has i there

#

that explains the "middle"

gray anchor
#

Oh! I doubt it is supposed to be. So yeah, looks like an error. Let me see if it fixes then! And yeah, ti does. Because the 1 would then be the 'second heart' right? 0-1-2? (I think I am understanding!)

strong wren
#

!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

rich adder
#

yes arrays are 0 index so 0 = 1st

gray anchor
#

Thank you both very much! That indeed was the issue. Now I can move onto the next part. XD I swear, this 3 hour tutorial is going to take me 15 or so hours total hahah. But it's worth it! I'm definitely learning.

bright arch
#

hey all:
destroying gameobjects should be the last resort, is that right? especially for ui elements?

keen dew
#

It's not quite that black and white

#

Most of the time there's nothing wrong with disposing of objects that aren't needed anymore by destroying them

naive pawn
#

absolutely not what this server is for

keen cargo
#

Not a code question

strong wren
#

!warn 619005684557545472 Keep it relevant to the server

eternal falconBOT
#

dynoSuccess soulcelestial has been warned.

naive pawn
#

you can code in $0 with the pinned resources

keen cargo
#

People do object pooling in that instance

bright arch
#

thank you :)

nimble apex
#

do loadscene by additive benefits from async/coroutine loading?

#

i use loadscene.single most of the time because i only need to switch from scene A to scene B

naive pawn
#

wdym by "async/coroutine loading" and wdym by "benefits"?

nimble apex
# naive pawn wdym by "async/coroutine loading" and wdym by "benefits"?

we use async or coroutines to load a scene because switch from scene A to scene B might need to load tons of stuff, so we pre-load the scene using async beforehand, and maybe we include some cinematics or loading animation to cover up the loading, once its loaded we just jump to other scene

#

thats the benefits right?

#

but what about if we load scene by additive?

naive pawn
#

you don't use coroutines to load a scene

sour fulcrum
#

additive just doesnt unload the active scene

nimble apex
#

async

#

aight i think i know what to do , thx

#

👍

exotic fox
#

Hey all! I'm new to Unity (I've used other engines in the past) and am losing my mind with a simple issue.

I have a 2D project. I've added a sprite with a box collider 2d and attached a script with OnMouseDown implemented. No matter what I do I cannot get this to actually respond to mouse events

using UnityEngine;

public class box : MonoBehaviour
{
    void OnMouseDown()
    {
        Debug.Log("Clicked");
    }

    void OnMouseEnter()
    {
        Debug.Log("Mouse enter");
    }
}

Am I missing something obvious? I think this should be all that's required to get a sprite to react to mouse events right?

#

I've tried changing the include/exclude layers on the collider, adding a rigid body, changing the collider size, etc. No matter what I do I never see the mouse events happen

wintry quarry
#

Look into IPointerDownHandler and IPointerUpHandler

#

The ones you're trying to use don't work with the new input system afaik

#

(you will also need to put an Event System in the scene and a Physics Raycaster 2D on your camera)

jaunty trellis
#

Hey! What is the differences between using Rigidbody vs not for character movement? (working in a 3D environment)

wintry quarry
#

Rigidbody is simulated in the physics engine

jaunty trellis
#

I'm not sure what alternatives there are to rigidbody but I know character controller has .Move()

jaunty trellis
wintry quarry
#

It behaves like a physical object

jaunty trellis
#

what alternatives are there to creating movements than rigidbody then?

wintry quarry
#

Infinite alternatives

#

You can do anything you want in your code

exotic fox
#

Thank you @wintry quarry! That fixed it. It's wild that I didn't see anything about this when googling. I was only seeing references to the old system. Is this a relatively new change?

wintry quarry
jaunty trellis
wintry quarry
#

I'm not sure what you're actually trying to ask here.
I think what you should do is follow a few different tutorials that use different approach (Rigidbody, CharacterController, KCC package) and get a feel for them maybe

#

But you're just going to have to try a bunch of ways to understand

#

Also note that "make a character move" is extremely vague

#

Every game has a unique idea about what that means

#

There are grid-based strategy games, platformers, physics puzzlers, etc.

jaunty trellis
#

yeah, I want to research and code some things, and since I'm pretty new I wanted some orientation

#

I'll look up documentation about rb's cc's and kcc

#

ty

crisp furnace
#

Hello

#

I have this little line of code here:
`BodySprite.transform.localRotation = Quaternion.FromToRotation(Vector3.up, walkNormal);

#

walkNormal is the normal of the surface that my body object is scanning with a hitscan

#

the purpose of this script is to turn the player body facing according to slopes etc. on a surface

#

my problem is: If i turn the camera 180° around the character, the sprite rotates with my camera object

#

and then if I walk up a slope, it is adjusted to the slope- however oddly enough mirrored by the Z axis instead of just being aligned to the normal

#

why does this happen? Quaternion should organize the facing in 3D space based on 3D space core coordinate system no?

naive pawn
#

are you working in 2d or 3d

floral wren
crisp furnace
crisp furnace
naive pawn
#

ah

crisp furnace
#

sry xD

naive pawn
#

are they sprite renderers or what exactly?

crisp furnace
#

no they are sprites

naive pawn
# crisp furnace

also what's the intended view if you look at this scenario straight-on, like, 90°?

crisp furnace
#

just 2D figures having a good old parapppa the rapper time in 3D land

naive pawn
#

sprite renderers or images or some other third thing

crisp furnace
#

oh yeah they are sprite renderer components

crisp furnace
naive pawn
#

yeah the sprites would turn into lines in that scenario, right

crisp furnace
#

it has a limited up and down angle and cant go lower than 0°

#

yes

#

So all in all the sprite is rotated with the camera

naive pawn
#

yeah that's why the 180° scenario doesn't have it rotated

crisp furnace
#

BodySprite.transform.up = walkNormal works great btw but now it has the issue where the sprite turn to lines

naive pawn
#

and it squishes when you look at it from like 30° right

#

do you want that effect?

wintry quarry
crisp furnace
#

I suppose what I need is a method that sends raycast fromt he camera to the surfaces too

wintry quarry
#

you said 360 orbital cam buit these are sprites, right?

#

So are the sprites supposed to billboard?

crisp furnace
#

yeah but only along the Y axis

#

if you move up and down, there is a bit of a limit on how far up the camera goes

#

so the sprite will just be seen in a bit of "depth of field" squishing, revealing its 2D-ness

#

that is all intended and good

wintry quarry
#

Ok so then like...

Vector3 camForward = Camera.main.transform.forward;
camForward.y = 0;
camForward.Normalize();

BodySprite.transform.rotation = Quaternion.LookRotation(camForward, walkNormal);```
#

this should do it i think

crisp furnace
#

Hmm so this takes the cameras forward vector

#

deletes y component

wintry quarry
#

yes, for the billboarding

crisp furnace
#

normalizes to (1,0,1) ish

#

how does the Quaternion.LookRotation() work?

#

It takes two vector 3

wintry quarry
#

yes the first one is the resulting object's blue (forward) vector

#

the second one is its yellow (up) vector

crisp furnace
#

ok

wintry quarry
#

since it's a sprite blue should be facing away from the camera

crisp furnace
#

huh thats cool af

wintry quarry
#

hence using the cam forward

crisp furnace
#

Quaternion is defined like this right? One forward and one upward vector (base vector)

wintry quarry
#

no

#

but this is one way to construct them

#

it happens to be convenient here

crisp furnace
#

Yeah

#

It works

#

Thank you PraetorBlue for sharing this method (constructor?) for Quaternions with me

#

It solves the entire issue with these 5 lines of code

#

Absolute Cinema

wintry quarry
#

Awesome, glad to be of help

crisp furnace
#

To understand this for the future, the Quaternion object is created and then inherited into rendering?

#

I only know the term constructing from object based programming

#

Quaternions confuse me and overwhelm me lol

wintry quarry
#

It's not technically a constructor, but it behaves exactly like one

#

Unity could have written this as a constructor if they wanted to

#

we are constructing the Quaternion object after all, just with a descriptive name.

#

Quaternions are less confusing when you think of them just as a piece of data that represents a rotation

#

similar to how a Vector3 is a peice of data that can represent a position

crisp furnace
#

yeah

wintry quarry
#

you don't need to worry about what's "inside" so to speak, it's not important

crisp furnace
#

I thought Quaternions are essentially a Vector3,Vector3,Float

wintry quarry
#

they're stored as just 4 floats

crisp furnace
#

where the first attribute is the location, second the rotation, and then there is a scale

wintry quarry
#

no, you're maybe confusing Quaternion with a Matrix4x4

#

Quaternion is just a rotation

crisp furnace
#

alright

wintry quarry
#

Matrix4x4 can store position, rotation, and scale

crisp furnace
#

Ooooh I think I got it

#

its a rotation but vector-like

#

instead of having a fixed 360° clock

#

so if I want to turn to the right, I go: (0,1,0,probably Pi?!) Turn me around Y, for this and that amount

wintry quarry
#

Like I said, don't think about the actual internals and numbers of it

#

it's complicated and not really important

crisp furnace
#

ok sadblob

wintry quarry
#

if you want to rotate around the y axis you can just use those "constructors" Unity provides

#

e.g. Quaternion.Euler(0, degreesToRotate, 0)

#

that creates a quaternion that rotates that number of degrees around the y axis

polar acorn
#

Quaternions literally use imaginary numbers. It's a four dimensional vector in the complex-real space.

Do not attempt to make sense of how the values of a quaternion translate into anything tangible

rocky canyon
naive pawn
#

see 3b1b's video on visualizing quaternions to see how mindfucky they are

#

and then decide to treat them as a blackbox from then on out

fair shore
#
   void Awake()
   {
       private Tilespawnner tiles = FindObjectOfType<Tilespawnner>();
       private GameObject[,] tilearray = tiles.spawnners;
   }

for (int x = 0; x < width; x++)
{
    for (int y = 0; y < height; y++)
    {
         * tile = tilearray[x, y];
        if (y < maindict[GameObject.Find(dragged.ToString())][2])
        {
            tile.tag = "Opened";
        }
    }
}
``` I got null reference exception at * line but i don't know the reason why I got it. When i debug the line, it is not debugging.
polar acorn
wintry quarry
polar acorn
#

You have access modifiers inside of a function

wintry quarry
#

also yeah this won't compile

fair shore
#

access modifiers? how to do it?

wintry quarry
#

how to do what exactly?

#

fields need to be declared outside of any methods.

polar acorn
fair shore
#

No. I declare fields outside my methods tho. but i write the fields there just to see the fields of the variable.

polar acorn
eternal falconBOT
polar acorn
#

so we can try to solve the problems you actually have

wintry quarry
polar acorn
#

instead of trying to figure out what is actual code and what is fluff

fair shore
#
    private Tilespawnner tiles;
    private GameObject[,] tilearray;
     void Awake()
   {
       tiles = FindObjectOfType<Tilespawnner>();
       tilearray = tiles.spawnners;
   }
   

public void OnDrag(PointerEventData eventData)
    {
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                tile = tilearray[x, y];
                if (y < maindict[GameObject.Find(dragged.ToString())][2])
                {
                    tile.tag = "Opened";
                }
            }
        }
    }
 ``` Here
wintry quarry
fair shore
#

How to make it not null then?

wintry quarry
#

assign it to something not null

#

you did this:
tilearray = tiles.spawnners;
but tiles.spawnners was probably also null

#

so you just assigned it to null there

#

Probably a script execution order issue, since you're doing this in Awake

#

and there's no guarantee that tiles has itself been initialized yet.

#

I actually don't see any good reason you need the private GameObject[,] tilearray; variable at all

#

you can just do tiles.spawnners directly when you need it

#

so delete the tilearray variable completely and replace:
tile = tilearray[x, y];
with:
tile = tiles.spawnners[x, y];

frigid sequoia
#

How is this ambiguous? They are quite literally, the same parameter wtf?

brave robin
slender nymph
#

also make sure you don't have a duplicate script

polar acorn
frigid sequoia
#

Oh, yes, I renamed the freaking class intead of the reference by mistake

#

What a mess

odd remnant
#

I've got a question about vehicles. When designing the code for a vehicle that players enter and control, who is doing the moving? The player? Or the vehicle? Which object should be converting inputs into movement? If it matters, vehicles might sometimes have multiple players in them, and/or NPCs.

#

My hunch says the player is converting inputs into actions, but the actions are vehicle methods.

hexed terrace
# odd remnant I've got a question about vehicles. When designing the code for a vehicle that p...

Your input should be separate from the thing that is being moved, all that you do is change the target transform/ rigidbody which the inputs control.

input -> target is set as player -> moves player around
player enters vehicle -> input target swaps to vehicle -> vehicle moves around
player exits vehicle -> input target swaps back to player

Having mupltiple players in them isn't going to affect that, just the first person in gets control of the vehicle

odd remnant
#

Got it. That makes sense and was along my lines of thinking. When you say "Input Target swaps to Vehicle", do you mean swapping to a different action map in the Input System?

#

Or do you mean that somehow there's a logical component that manages "what the player is controlling" - FirstPersonController or Vehicle

brave robin
#

Like aircraft would have different controls from cars

odd remnant
#

Forgive the sloppy whiteboarding:

#

This is how I understand it to work, but I'm not certain.

#

So the InputSystem has various ActionMaps for different vehicles (right now I'm working on an emplacement that players can rotate with the mouse of thumbstick, and click to shoot)

#

My first person controller uses mappings from the "Player" Action Map. And my emplacement would use mappings from the "Emplacement" action map (above that's "Vehicle")

#

I sort of understood that there should be some "Player" object that sits between these two that literally defines the player themselves, whether they're controlling a FPS character, or a vehicle, that toggles between the "input target" of the player, and the "input target" of the vehicle.

#

Is that...remotely on-track?

brave robin
#

You could do it a number of ways. Like when the player enters a vehicle you can just turn off the script(s) on them that are listening for input, and enable the one on the vehicle. As long as the player is attached to the vehicle somehow, either by parenting or using a position constrait and rotation constraint (I prefer constraints, less messy than parenting), then the vehicle will carry the player around.

jaunty trellis
#

when using a CC, does it matter if i disable the colliders of the player-object that the CC is attached to?

late burrow
#

how can i make field in class where when i change it it also changes all memberwisecloned classes

naive pawn
jaunty trellis
#

I'm exploring different options of how I could move a character, starting of with CC, then going to RB

#

So, if I use a CC, I should delete the colliders of the objects child/parent to the CC

#

I didn't add the collider, just came with the capsule

polar acorn
#

CharacterController serves as a sort of ad-hoc collider on its own

#

You wouldn't have any other colliders on it if it has a CC

jaunty trellis
#

I see, thanks

frigid sequoia
#

This should be checking if a point of the NavMesh exists within 0.1 of the candidate point right?

#

I am not sure if I understood this method right

jaunty trellis
#

With a CC, what should I do to rotate the player? transform.Rotate or smthn like that?

#

Because the .Move() is pretty neat, but I can't seem to find any similar method for rotating

hexed terrace
#

what do the docs say?

jaunty trellis
#

Not sure if you responded to me Carwash, but CC docs don't say (as far as I've seen ofc)

hexed terrace
#

aye, just looked.. doesn't say.. because ye know, that wold be useful

wintry quarry
#

Note that you can't really rotate it except on the y axis

frosty hound
#

There is no concept of rotation with the CC, you have your velocity which you steer into a given direction (rotate the vector).

wintry quarry
#

The CC is always upright

frosty hound
#

If you're referring to the visuals of the player, that also has nothing to do with the CC. You simply handle that however you want, such as lerping the forward direction of the model towards the velocity of the CC.

jaunty trellis
#

Yeah I find a lot of methods that I'm guessing can be used to rotate an object based on input. += new Quaternion. SetFromToRotation, SetLookRotation, RotateTowards, Slerp, Lerp, (all Quat.Euler ofc). Then also the Transform.Rotate. Do they all work? any I should avoid or is better?

frosty hound
#

Vector3.Lerp, Quaternion.Slerp (which I think I'm currently using for a simple CC)

jaunty trellis
#

Would that be a Quaternion.Euler.Slerp? or do you use the actual Quaternions?

frosty hound
#

transform.rotation is a Quaternion, yes

jaunty trellis
#

Because I don't think I will understand them good enough to use

#

I watched a 3b1b video about it and it looks so confusing (4d rotation?!?)

frosty hound
#

You don't need to actually know how Quaternions work, nobody really does.

#

Unity has built in functions for handling them for you.

#

And ways to convert simple Euler to Quaternions.

twin pivot
#

I wonder how they made those functions

#

did unity hire people that do know how quaternions work?

polar acorn
twin pivot
#

dark magic I tell you

naive pawn
rich adder
frigid sequoia
rich adder
frigid sequoia
#

I did read that

#

I was not sure of what I read

#

So I asked

rich adder
#

no worries nothing wrong in asking for clarification

jaunty trellis
#

Is the Quaternion.Slerp the same as the Vector3.Slerp? (if you convert the Quaternion into Quaternion.Euler? maybe)

polar acorn
#

It gets you a Quaternion that is some percent of the way between two others

wintry quarry
#

You can't use Slerp with Euler angle vectors

#

Well you can but it's not really going to give you the correct results

jaunty trellis
#

hm. So, I'm confused. Say that I want to use the Vector3.Slerp function to rotate my char based on input. How would I do that? Do I acess the objects rotation via transform and equal it to a Vector3?

#

This sounds so basic, I don't know why I can't connect the dots myself

polar acorn
rich adder
#

if you do transform then something like transform.rotation = quaterion.slerp ( quaternion.euler( etc

jaunty trellis
#

but then to set rotation I'd still do playerTransform.Rotate(Vector)

rocky canyon
jaunty trellis
#

So in the end its all just transform.Rotate?

polar acorn
rich adder
#

no not .Rotate

jaunty trellis
#

ooooh, so there are two options then. 1) directly .Rotate 2) to change in the transform.rotation?

rich adder
#

transform.rotation = quaterion.slerp ( currentRot , targetRot

jaunty trellis
#

I'll play around with that exact formulation, tyty

jaunty trellis
rich adder
#

always quaternion. if it was stored as Vector3 it would break and experience gimbal lock

#

but you can do .eulerAngles on any Transform or Quaternion

rocky canyon
#

if u swap ur inspector to Debug. u can see the Extra W property 👀

#

hehe..not very useful.. but yea rotation is a quat

rocky canyon
#

unless im using one of unity's nifty methods where i dont need to 💪

rich adder
#

you would be a madman to do anything with quaternion floats heh

#

Quaternion helper methods are very nice, like Mathf. leave the heavy math to someone else lol

rocky canyon
#

Darhk ^ may be the only thing u need is ur input a degree's per second variable and Mathf.MoveTowardsAngle but dont know the specifics ofc

jaunty trellis
#

yo thats sick! WIll check out

fathom echo
#

hi! still working on my flappy birds. It works almost fine but when the bird dies it restarts from where it dies, without resetting all the pipes and bird position...

rocky canyon
#

reload the scene?

fathom echo
rocky canyon
#

thats desired tho right? u dont want the game to start until u press the button indicating ur ready to play right?

fathom echo
#

yep

#

i put the reload scene in the game over function

#

but It doesn't resets

#

SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex);

#

i should use this?

polar acorn
polar acorn
#

Show the !code where you call that

eternal falconBOT
fathom echo
ivory bobcat
polar acorn
polar acorn
#

The whole window would include the hierarchy

#

and also the console

#

and probably inspector

polar acorn
#

Check that error

#

see what line it's on

fathom echo
ivory bobcat
#

Just for future references, when you get an error during runtime, expect things to not work as expected (producing undefined behavior)

polar acorn
#

Errors mean the function ends immediately

#

so nothing after that line runs

fathom echo
#

The player variable doesn't contain any player...

ivory bobcat
fathom echo
ivory bobcat
#

Seeing the error and stack from the console would be useful

ivory bobcat
polar acorn
fathom echo
polar acorn
ivory bobcat
fathom echo
polar acorn
fathom echo
ivory bobcat
polar acorn
#

So of course you cannot drag it into a slot that expects a Player component

ivory bobcat
fathom echo
#

ohhhhh I'm burned

#

I was seeing how some people did the script and they eventually called the birdcontroller "player"

#

thanks you everyone sorry if I bothered you with that stupid problem..

ivory bobcat
#
public BirdController player;```
fathom echo
ivory bobcat
#

Likely so. Zero errors would have the scene loading statement behave as expected (destroy and recreate the scene with it's default parameters)

jaunty trellis
#

Okay, so I know Move() should be FixedUpdate() but the camera jitters substantially more than if I also run it in Update(). Is this bad?

ivory bobcat
jaunty trellis
#

I'm using a CC, the scene is a plane + 2 cubes that are stationary and I'm walking around + moving camera to test jitters

#

the camera is attached to the player with a child object

#

Anyway, are there any negatives with running the Move() code inside of normal Update()?

ivory bobcat
jaunty trellis
#

well basically its just the cc.Move() function

#

even if I code for input accumulation it doesn't improve the jitters

#

the difference is actually night and day

ivory bobcat
#

If you decouple the camera from the player, does the player move appropriately?

jaunty trellis
#

i mean yes, but the point is the camera being jittery, and that (Im 99% sure) is caused by desync in player movement and camera movement

#

because of inputs being recorded frame-by-frame and then Updated with FixedUpdate() is not frame-by-bframe

ivory bobcat
#

With RB physics, you'd be able to move the player using interpolation and also move the camera in late update to avoid jittering issues. I'm unsure about CC.

jaunty trellis
#

What happens if you DONT move a RB body in Fixed?

#

Just asking

earnest wind
#

am i doing something wrong here?

WWWForm form = new();
form.AddField("PhotonApplicationId", "--");

UnityWebRequest webRequest = UnityWebRequest.Post("https://---.playfabapi.com/Client/GetPhotonAuthenticationToken", form);
webRequest.SetRequestHeader("Content-Type", "application/json");
webRequest.SetRequestHeader("X-Authorization", ClientSessionTicket);

await webRequest.SendWebRequest();

this just gives a UnityWebRequest.Result.ProtocolError Debug.LogError("HTTPS Error: " + webRequest.error);

ivory bobcat
earnest wind
#

i can share more info if needed

jaunty trellis
#

Entirely possible the networking channel knows more about Photon (i think)

earnest wind
jaunty trellis
#

I wish I could help you, but I've only dabblewd with Fish-net as multiplayer ;/

fathom echo
ivory bobcat
earnest wind
#

its fine Darhk, thanks for atleast chatting lol, i went on and asked in the playfab server ig

ivory bobcat
#

So why would it think your bird has died?

fathom echo
jaunty trellis
ivory bobcat
earnest wind
#

thats from my debug btw

switch (webRequest.result)
            {
                case UnityWebRequest.Result.ConnectionError:
                    Debug.LogError("Connection Error: " + webRequest.error);
                    return null;
                case UnityWebRequest.Result.DataProcessingError:
                    Debug.LogError("Error: " + webRequest.error);
                    return null;
                case UnityWebRequest.Result.ProtocolError:
                    Debug.LogError("HTTPS Error: " + webRequest.error);
                    return null;
                case UnityWebRequest.Result.Success:
                    string json = webRequest.downloadHandler.text;

                    GetPhotonAuthenticationTokenRequest response = JsonUtility.FromJson<GetPhotonAuthenticationTokenRequest>(json);
                    return response;
            }
grand snow
#

time to learn about http status codes

earnest wind
grand snow
#

can a www form be used with json? 🤔

earnest wind
#

for other things, not for playfab

hallow sun
#

idk much about this, but is ---.playfabapi.com correct or just a placeholder you forgot to replace?

earnest wind
#

thats where the title ID is

#

i would get a different type of error if the url would be incorrect

grand snow
#

If the content should be json then you should encode json yourself

teal viper
ivory bobcat
# jaunty trellis Using RB, should my Rotate() still be using Update() or no?

Reminder that using RB physics will have your objects simulating actual rb physics. You'll get cheap freebies (collision and trigger detection/behavior) but also have to fight whatever comes with actual rb physics that may be unwanted for video-game-physics/non-rb-physics (friction/sliding, high speed collision detection issues, etc)
Unfortunately, I'm not sure how to fix your original jittering camera issue with CC.

grand snow
# earnest wind wdym by that

you set the content type header to json but give a www form which should actually be used with application/x-www-form-urlencoded (as the content type)

earnest wind
#

im gonna save and check the debug for error

#

one sec

earnest wind
#

if you say that www form wouldnt work with the json response

jaunty trellis
#

am i dumb, why isnt this block falling when using RB?

grand snow
earnest wind
grand snow
#

i dont know what this api wants but you need to give the correct content type header for what you send. If you say its json then send json...

earnest wind
#

it says i should send this

#

string and string

#

also i checked the debug.log for error

grand snow
#
{
    "PhotonApplicationId": "foobar"
}
#

just try with a pre made json string firstly

earnest wind
#

will try what u said in a minute

#

okay

grand snow
#

you can use JsonUtility to serialize a class to json or use Newtonsoft JSON to serialize a Dictionary<string, string> to json

earnest wind
#

i need to listen to you xD

#

im sorry i was wrong 😭

grand snow
#

stop using a www form

ivory bobcat
jaunty trellis
#

no I checked that

earnest wind
earnest wind
#

oh my god i sent the app id and all 😭

#

i shouldnt rn since i didnt finish this yet 😭

grand snow
#

if you sent your api key time to make a new one

earnest wind
#

photon itself said you dont have to protect it, to protect you need to add authentification to the app

earnest wind
ivory bobcat
jaunty trellis
#

no, the same set up works in a clean project some it has to be a setting of sort

#

wonky shite

grand snow
jaunty trellis
#

that was it, why the fuck was it set to that

#

I've spent AN HOUR debugging this

earnest wind
grand snow
earnest wind
#

cause it still gives the same error :/

mild lake
#

Why are public variables bad? I've been working around them just because i've heard they're not good to use, but why?

earnest wind
#

wait

#

give me 1 minute

earnest wind
ripe shard
earnest wind
mild lake
sour fulcrum
#

The idea being other things shouldn't be allowed to touch them directly, rather than public fields it's preferable to have a public function that gets and sets that value or a property by doing

[field: SerializeField] public Type myVariable { get; private set; }

sour fulcrum
#

in theory if i see a public variable its a sign that I should be allowed to touch that without fear of things breaking

#

which means that value either needs to be safe to mess with or protected from things messing with it

ripe shard
mild lake
#

gotcha, so it's just good practice

sour fulcrum
#

yeah, it doesnt matter at runtime or anything

mild lake
#

i have my private variables, then public variables that get the private variables right now

    {
        get => moveSpeed;
    }
sour fulcrum
#

in that case you probably just want an auto property

#

which is that but simplified

earnest wind
#

i fixed it, thanks a lot rob5300 if you see this message by any chance

mild lake
# sour fulcrum see here

Gotcha. Thank you much, that's a whole lot cleaner

[SerializeField] public float MoveSpeed { get; private set; } = 5;

sour fulcrum
#

you need the [field: SerializeField]

#

basicially Unity doesn't serialize properties but if it's a auto property and you tell unity to explicitly treat it like a field it works

mild lake
#

[SerializeField] and [field: SerializeField] aren't the same thing?

sour fulcrum
#

the latter targets the backing field of the property iirc

sour fulcrum
#

you gotta tell unity to care about the private one

mild lake
#

Gotcha gotcha

sour fulcrum
#

but yeah either autoproperties with differing protection accessors or explicit functions that deal with getting and setting are almost always preferable to just a public field

ripe shard
ember tangle
#

I have an action in a class A:
public Action OnCollide;
I assign a function to it from another class in an intermediary class:
A.OnCollide += B.SetCollisionMarker;
I call the action:
OnCollide?.Invoke();
and the function in class B is never called.

What did I do wrong?

slender nymph
#

that's not really enough context to know what you did incorrectly. share the actual code

ember tangle
#

Class with action:

public class PhysicsBody : MonoBehaviour
{
    public Action OnCollide;

  private void OnCollisionEnter(Collision collision)
  {
      Debug.Log("collide"); // this works
      OnCollide?.Invoke();
  }
}

function where action is assigned:

{
    foreach(var body in PhysicsManager.instance.bodies)
    {
        
        GameObject trajObject = Instantiate(trajectoryBodyPrefab, this.transform);
        PhysicsBody trajBody = trajObject.GetComponent<PhysicsBody>();

        trajBody.mass = body.mass;
        trajBody.velocity = body.velocity;
        trajBody.rigidbody.position = body.rigidbody.position;
        trajBody.transform.position = body.transform.position;

        trajBody.name = $"trajBody_{body.name}";

        GameObject trajLine = Instantiate(trajectoryLinePrefab, this.transform);
        TrajectoryLine line = trajLine.GetComponent<TrajectoryLine>();

        line.name = $"trajLine_{body.name}";
        line.body = body;
        line.simluatedPhysicsBody = trajObject.GetComponent<PhysicsBody>();
        trajectoryLines.Add(line);

        trajBody.OnCollide += line.SetCollisionMarker;

    }
}```


class where desired function exists:
```public class TrajectoryLine : MonoBehaviour
{
  public void SetCollisionMarker()
  {
      Debug.Log("SetMarker"); //does not work
  }
}```
slender nymph
#

just printing "collide" is not useful at all, consider printing some more info, like what object is invoking the event. then you can do some more debugging to figure out why that object does not have anything subscribed to it

#

and also make sure you aren't ignoring/hiding any exceptions in the console

ember tangle
#

Gotcha. But I'm using the action and invoking it correctly?

#

minus whatever spaghetti is stopping it?

wintry quarry
#

I would recommend using the event keyword here but otherwise yes

ember tangle
#

why event over action?

wintry quarry
#

My guess is that the instances you're subscribing to are not the same as the ones that are colliding

wintry quarry
#

You still need Action

#

event just means that only the class that owns it can invoke it

#

Or reassign it

#

public event Action OnCollide;

#

By adding the event keyword here we might even reveal the issue if it leads to a compile error somewhere.

twin pivot
#

I have no idea what this is referencing

rich adder
twin pivot
rich adder
bold plover
#

Ok I think it's an error with the order of execution but for whatever reason my player isn't physically jumping despite the line of code being called. I feel like I'm missing something obvious. Again the line says it executes but I'm not getting the jump itself.
https://hastebin.com/share/edikejujok.java

bold plover
sour fulcrum
#

ghetto isn't a suitable word in that context

bold plover
#

yeah, you're right

eternal needle
twin pivot
north kiln
#

Floating point inaccuracy means you should almost always either do Mathf.Approximately (if you expect that the two values are actually approximately close), or use a larger threshold like if (Math.Abs(a - b) < TOLERANCE)

twin pivot
north kiln
#

Vector2.Distance(, that's a float.
_player.transform.position.x that's a float.

twin pivot
#

Oh shit ur right, thanks

tiny bloom
#

I am spawning enemies only on server/host
player1 starts the game, clicks start host, set itself in a Manager as a reference being the host player and enemies start spawning, take the reference from the Manager, and start following this reference on update

I let this run for a minute and it's fine
but when player2 joins as a client, for some reason it throws an exception on player2 console that the script EnemyFollowPlayer has a null reference of target player to follow
even though the enemies are set to only set to spawn on the server

any idea what's going on? please note this suddenly starting happening today it was running fine before

eternal needle
lean shadow
#

Hey yall, i have a problem I could not solve even with the help of chatgpt+ and countless debugging hours. The code in the pictures are all in different scripts, the problem I have is the third picture with the Debug.Log("Before...") and Debug.Log("After...").

For Example:

When newID gets a new id with the help of ItemInformation.Instance.GetNewItemID(), it works perfectly fine, the GameObjects kxInfo and cxInfo get the correct ID. If I have 3 gameobjects the instantiated objects (GameObject kxInfo = Instantiate(ItemInformation.Instance.kxInfoPrefab, ItemInformation.Instance.gameObject.transform);) look like this:

1000
1001
1002

And the logging looks like this:

Before:0
After:1000
Before:0
After:1001
Before:1001
After:1002

This makes absolutely no sense to me and if I look at the instantiated gameobjects then they have the following ids:

1000
1002
1000

which is even more confusing to me. Goal is to have the same ID as the instantiated kxInfo/cxInfo Objects.

I hope i could explain my problem somehow understandeable with my broke english

eternal falconBOT
naive pawn
#

please share your code as specified above ^

#

real quick, what part are you confused about? what's happening, or why it's happening?

#

the logs and ids you've shown seem to be pretty self-consistent
they point to an issue, yes, but they point to the same issue

#

it seems pretty clear to me what's going on, but it'll be hard to confirm/explain without seeing how all the methods flow, so it would help if you could share more complete scripts to show that via the links above

lean shadow
#

shall I also record a video?

hexed terrace
#

haven't shown where GetNewItemID() is called either

lean shadow
#

and second

hexed terrace
#

ah, missed it all the way up there right at the top of 2nd pic

lean shadow
naive pawn
wintry quarry
naive pawn
#

there are logs in the 3rd image but it doesn't show where it's being called from

wintry quarry
#

Not knowing which script everything is in hurts

lean shadow
lean shadow
naive pawn
#

you're good, we've all been there

lean shadow
#

how can I show yall my screen recording

#

ill setup a drive link to my screen recording if you want to look at it

#

so u understand the problem better if yall trust me that much

naive pawn
#

so seems like the second and third objects you place have the same name
so when you go to place them, you call shelves[currentShelfIndex].PlaceItemInShelf with those same-named gameobjects
then PlaceItemInShelf passes those to ItemGridItems.Instance.AddCorrespondingItem
then AddCorrespondingItem gives you gameObjects based on the name - and since in the second and third instance, they have the same name, you get the same prefab back
back in PlaceItemInShelf, that means you're getting the same gameobject twice - so you see the second object getting overwritten with the third ID

#

does that sound about right?

#

the other option is that maybe you accidentally set multiple of the "prefabs" in ItemGridItems to the same GO

wintry quarry
#

Too much reliance on strings and object names

naive pawn
#

but if they're actually prefabs, well, you never call Instantiate on them, you just use them directly?
that seems like a much deeper issue

lean shadow
#

i know that I get the prefab, but thats why i try to set the ID here:

GameObject objToGive = ItemGridItems.Instance.AddCorrespondingItem(objToPlace);
objToGive.GetComponent<ShelfItemHandler>().ID = ID;

lean shadow
naive pawn
#

like how are those 2 statements related

#

are they actually prefabs? if so, you probably shouldn't be editing them, but editing instantiated versions

lean shadow
#

here i get the prefab

GameObject objToGive = ItemGridItems.Instance.AddCorrespondingItem(objToPlace);

and then I set the id of the objToGive
objToGive.GetComponent<ShelfItemHandler>().ID = ID;

which is then stored in the List<Gameobject> and that list is used to instantiate the items in a different script with a foreach.

naive pawn
#

do you know what a prefab is

#

you can think of it as a template of a gameobject

lean shadow
#

AddCorrespondingItem(objToPlace) gives me the prefab you sav the code to that script

naive pawn
#

you shouldn't be modifying the template

lean shadow
#

yes but I modify the objToGive?

naive pawn
#

which is, apparently, a prefab

lean shadow
#

oh god damn wait a minute