#💻┃code-beginner

1 messages · Page 401 of 1

dense plume
#

that's your cuplrit.

astral basin
#

ohhh

dense plume
#

Click it and set it literally anything else

astral basin
#

ok its on center now

#

lets see

#

yeah that works

#

thank you

#

alot

dense plume
#

You bet good luck

dark sluice
#

your a lifesaver

astral basin
#

fr he is

dark sluice
#

its always something so simple that im missing stg

dense plume
#

No worries I been doing this 15 years and sometimes I still forget to assign things in the inspector

dark sluice
haughty copper
#

RPC trouble

glacial blade
#

anyone know how to fix this?

spare mountain
glacial blade
#

😦

brisk flume
#

how should i start learing code
is it by learning c# alone and then make games using it or the other way ??

plush vessel
#

I have a native unity app running in the background of my quest and this app will launch the browser onto this device and run in the background, and now this app is not listening to the user speech in background, and is not playing audio, how can I solve this

quartz nimbus
#

so I have this code written down to respawn my character when it is destroyed but even when it is destroyed it dosent respawn can I get some help with this thanks

#

also its followed by this error

raw token
# plush vessel I have a native unity app running in the background of my quest and this app wil...

If by "quest" you mean the Oculus/Meta VR device, that seems like a question which you should maybe direct to the #🥽┃virtual-reality channel. If that is not what you meant, I think you should probably elaborate upon what you mean by "native Unity app" and "running in the background of my quest," as well as which devices you are talking about, and how you are listening for user speech to begin with.

green ether
quartz nimbus
green ether
#

Well

#

i see it now

#

You check if character is null

#

and then use it

#

If its null you cant instantiate it

quartz nimbus
#

oh ok than how would i fix that problem

green ether
#

The way I would do it is to have something in the players OnDestroy()

#

for example in the playerScript in OnDestroy you start this coroutine in Respawn.
And then you reference the PlayerPrefab instead of the actual player and spawn it after x sec

#

Also has the advantage that you arent checking wether the player is null every frame

#

The above would otherwise also start a new coroutine every frame and spawn alot of new players

#

Every frame for 2 seconds till the first player spawns a new coroutine would start

quartz nimbus
#

tysm for the help

green ether
#

Depending on your game, actually destroying the player could lead to problems though. Depending on how coupled everything is

#

It could potentially be easier to just hide the actual graphical aspect and disable controls or something

#

But that depends on your situation

raw token
#

On a tangent, I'm really curious about what was responsible for the error here... Was it the coroutine call, or was it the Instantiate(Charchter)? Surely the former, as after two seconds Unity has certainly actually destroyed/GC'd the GO... Unless the flagged-for-destroy value was captured in the coroutine argument? 🤔

quartz nimbus
green ether
#

because this line will only ever be called if character == null

#

Therefore its guaranteed to throw an error because you cant instantiate(null)

ivory bobcat
green ether
#

what

ivory bobcat
#

It's been destroyed but you're still trying to access it.

green ether
#

yep

#

exactly

raw token
#

I'm just thinking that if the GO is Destroy()d in the same frame prior to this script's Update(), then it's not... actually destroyed yet. Just flagged for destruction at the end of the frame, no? It has an overloaded equality operation for null, but it's not actually null yet, yes? So like...

#

Ah I'll go test

green ether
#

Oh not sure about that myself actually

#

Thats why I would prevent all that and just do it in OnDestroy() or invoke some Death event

burnt vapor
ivory bobcat
raw token
quartz nimbus
burnt vapor
raw token
eager spindle
#

iirc the gameobject is inactive while being destroyed

#

you can do a check for that

green ether
#

Let me know how the test works out)

raw token
#

C# is not my native language 😁

burnt vapor
#

I doubt they like it themselves but after years of development these things will exist

raw token
# burnt vapor I doubt they like it themselves but after years of development these things will...

Absolutely! I... just sometimes have a weird preoccupation with the minute details of implementations. The details are mostly useless in practice, but I can't help but be a little captivated - at least when they're in my realm of understanding.

I think.... part of my fascination might be borne of time spent with the Hackmud community - a Unity game, where obscure knowledge of the weird edges of it's JS runtime/environment could allow you steal other players' riches.

neon latch
#

How can I make a model disable after 2 seconds of raycast casted from player’s camera hit the model?

green ether
neon latch
languid spire
#

for future reference, if someone tells you something you dont understand, Google it

green ether
#

Its useful if you want to do stuff across frames, like waiting some time to do x, then another wait and do y

#

Very basic explanation but yeah

neon latch
#

Ok thanks!

brisk flume
#

tips on making learning code less boring

quartz nimbus
#

how would i reference a void OnMouseButton() in another script for example to damage and enemy

languid spire
quartz nimbus
ivory bobcat
quartz nimbus
ivory bobcat
# quartz nimbus wdym

You shouldn't need to be calling this Unity callback function - it's managed by Unity.

green ether
#

But if you find code boring why learn it in the first place

brisk flume
green ether
#

I guess the first step is to go to a doctor to get diagnosed and see what you can do about that

brisk flume
#

i am diagnosed but its smth you gotta deal with

#

or take the medication which i dont have accesses to rn

green ether
#

Yeah I dont have much experience with it but figured there is some medication that might help

#

But if access to it is not possible thats unfortunate

brisk ruin
#

Guys I fell stuck and I don't know what to do I started learning weeks ago but I don't know the program to study and see progress

#

How you guys learn

#

What the steps u know

green ether
#

Pick something relatively easy you want to achieve and do it

#

Step by step, cut it into the smallest pieces and do one after the other

eternal falconBOT
#

:teacher: Unity Learn ↗

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

brisk ruin
#

I'm currently following Brackeys tutorials

languid spire
green ether
#

Dont just follow them like that

green ether
#

Do your own project and then look for tutorials for each step you get stuck on

brisk ruin
brisk ruin
brisk ruin
green ether
#

you dont need to

brisk ruin
#

Something simple and easy

green ether
#

For learning especially

#

Look for games that interest you/ you like and remake them

eager spindle
#

its fun to make

#

fairly quick to do

green ether
#

yeah that could also be a good plan

#

or classics like tetris/ pong/ snake and work up from that

eager spindle
#

i made a skibidi toilet fangame for fun and also learned a lot from that

#

i dont understand why this video has 780k views but its a fun project

raw token
# green ether Let me know how the test works out)

I haven't quite fully sussed this out but I need to sleep. My observations thus far are fairly sprawling and probably not entirely accurate. I think I need to play with it all another hour or so get a full grip on things. But this is what I observed:

Instantiate() with an argument of the real value null produces a distinct exception:

ArgumentException: The Object you want to instantiate is null.

After you Destroy() a GO, within that frame it's value and equality will evaluate as equivalent to null, but it's still a GameObject type, and you can apparently operate upon it within that frame and within that call stack without issue or repercussion (yet to test - destruction from a separate script... perhaps the flagging which is responsible for the exception occurs between script message invocations)... If you Destroy() a GO then immediately Instantiate() it, Unity will happily clone the destroyed object into the scene hierarchy without complaint.

On the next and all subsequent frames, it's still an actual GameObject which evaluates as null, but now attempting to Instantiate() it or otherwise interact with it as a GameObject will throw the MissingReferenceException exception...

So I'm still not certain where the code in question was generating the error, and I haven't yet tested the argument closure... But I suspect it is the Instantiate(Charchter), as it would reference the... post-destruction GO after the frame in which it's destroyed at that point.

But that'll have to wait for tomorrow 🫡

brisk ruin
#

Thanks yall I'll do that

eager spindle
eager spindle
#

when you Destroy an object, it cuts off all references in the project but hasnt destroyed the object.

green ether
#

Thanks!

eager spindle
#

not until the GC acts again, prob at the end of the frame

turbid quartz
#

i cant open unity after reinstalling my windows. i did install Visual C++ Redistributable tho and games that needed it are running just fine

languid spire
raw token
# eager spindle this is very interesting. its probably because the GC hasnt acted upon the objec...

Oh definitely! Like I'm sure this is all documented somewhere, and like 80 thousand people have done what I'm doing now... but 🤷

What I find most interesting is that bit which you point out - that it seems like Unity is still happy to treat the thing as a fully functioning GO until the end of the frame in which it's Destroy()ed, but it's not until the next frame that it seemingly starts throwing exceptions for member accessors (unless that change occurs in my yet untested scenario of the subsequent Unity message)...

eager spindle
#

but also interesting

#

i wonder if this is platform dependent and if it differs between .net and IL2CPP since they treat cases like this differently

#

ive had to deal with discrepencies between the two platforms a lot before

#

in fact I also had discrepencies between the editor and the game before

turbid quartz
languid spire
languid spire
#

yeah? Not 2010

turbid quartz
#

dayum. i thought later versions support older ones

#

thanks

vast vessel
#

nothing is null btw

green ether
#

its not crashing just because you add deltaTime to t

hexed terrace
#

It's probably in an infinite loop

verbal dome
#

It has a yield though 🤔

hexed terrace
#

I suppose disintigrationTime has a value as well actually

vast vessel
#

wait ill send a video

verbal dome
#

Are you messing with timeScale or anything?

vast vessel
#

no its 1

#

see?

#

thats where it crashes

hexed terrace
#

and if you comment out that while loop.. does it still crash?

vast vessel
#

ill try it

#

here is the config

languid spire
vast vessel
teal viper
languid spire
vast vessel
#

how do i find the infinate loop?

hexed terrace
#

so your crash is elsewhere

teal viper
#

Though depending on your os it might get shut down after a while

hexed terrace
#

It's not the infinite loop, I just didn't read your code properly

#

now comment out the mat.SetFloat(...

teal viper
#

Well, the log should probably have some info on the crash.

hexed terrace
#

you'd hope

teal viper
#

There aren't that many things that could crash an editor. The most common one is a GPU crash/hang. And that should be producing errors correctly

vast vessel
#

this code used to work before! idk why this is happening

void thicket
teal viper
vast vessel
#

the code is kinda old

vast vessel
#

ill change it

#

its not an issue tho

vast vessel
hexed terrace
#

check the logs first

teal viper
#

Are you just making random assumptions?

vast vessel
#

exactly

teal viper
#

How did you come to a conclusion that this code or it's base class is relevant?

raw token
#

I'd also like to know Who and When, just for completeness' sake

languid spire
#

missing the most important one, When?

hexed terrace
teal viper
#

Ok, that explains it. I don't think it was mentioned anywhere in the text though. Or I'm blind.

hexed terrace
#

not explicitly, but in his first msg he's got a screenshot with the breakpoints visible

vast vessel
#

i couldnt find anything in the editor log

teal viper
# vast vessel

That doesn't provide any proof that the crash is caused by the code though. You press continue, so it yields and probably continues to the next frame. There's probably a hell lot of a code running between you pressing continue and the crash.

vast vessel
#

how do you recomend i find the cause then?

teal viper
#

Or did you reopen the editor before copying it?

vast vessel
#

commenting this out fixed the crash. this is whats causing it.

#

btw its not the while loop, since commenting that out didnt fix the crash

hexed terrace
vast vessel
#

ik

burnt vapor
vast vessel
#

thats what im saying.

teal viper
vast vessel
hexed terrace
#

use MORE

teal viper
#

F11

languid spire
#

first thing I'd do is make sure you're not starting multiple coroutines

languid spire
#

prove it

teal viper
#

That being said, it's likely something you're doing to the GPU, so it crashes after the coroutine yields and the GPU processes the issue.

vast vessel
burnt vapor
# vast vessel i did use break points

Please store the result of Mathf.Lerp(startValue, targetValue, t / disintegrationTime) (line 54), and check its value before you call mat.SetFloat

#

My guess is that this is the issue, maybe

teal viper
teal viper
vast vessel
vast vessel
#

see?

#

start value is 0

teal viper
#

The value in the debugger

vast vessel
#

x is 0 in locals

quartz nimbus
#

why does a null reference appear when when I call this method from another script

teal viper
vast vessel
#

yield return null runs, then it hangs for a few seconds and crashes

teal viper
#

That would be a freeze.

vast vessel
quartz nimbus
#

here the error

languid spire
hexed terrace
quartz nimbus
quartz nimbus
hexed terrace
#

the NRE is in EnemyAI.cs -> on line 138 ... as @languid spire says, it'll be playerDamage

languid spire
# quartz nimbus

please use some common sense here. You've posted 2 snippets neither of which show the class nor the line numbers

quartz nimbus
#

sorry man

safe radish
#

i'm using heightValue = Mathf.PerlinNoise(perlinX, perlinZ) * perlinHeightMultiplier; for perlin noise but everytime i enter playmode i get the same output. how can i randomize the seed it is working from?

vast vessel
#

its so annoying having to open a project so many times just for it to crash again. it takes so fucking long!

languid spire
vast vessel
#

okay so this crashes

#

but this dosnt

#

its gotta be the materials

hexed terrace
#

narrow it down by commenting out less..

safe radish
#

tried using int seed = Random.Range(0, 100000); Random.InitState(seed); but it seems like the seed remains the same

#

i guess ill try to introduce a random scroll through the noise instead

#

ahh, i guess that is how it's supposed to be used

magic panther
#

this is a snippet of my script, and everything works perfectly well, besides the fact that nothing is getting Destroyed. Any idea on how to fix this?

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

languid spire
magic panther
#

I did but everything besides Destroy()s works

#

they're still there

hexed terrace
#

Use this
Debug.Log($"Destroying hole: {hole.gameObject.name}", hole.gameObject);

#

It will output the game object getting destroyed and if it's still around you can click the log and the GO will be pinged in the hierarchy

magic panther
languid spire
magic panther
#

what do you mean

#

it's an extra debug log you asked me to add

languid spire
#

no Debug.Log's here

magic panther
#

yes because you told me to add one

#

It seems to me the Destroy() functions are just not executing

#

how do I fix this

verbal dome
#

Btw Destroy(this) destroys this component, not this gameobject

#

Is that intentional?

magic panther
#

wait

#

bro I'm stupid

magic panther
#

added .gameObject to all destroys, all is working now

vast vessel
# languid spire then dont write code that causes crashes

i found the reason!
you see, on the line where i set the shared materials for my renderers, it was possible for the renderers to be a VFX renderer, which literally crash the game if you try to set anything on them. i ended up filtering them out from my renderers list.

languid spire
vast vessel
#

because it wasnt? it was on a loop for setting the shared material

languid spire
#

So you've just been posting crap

#

and wasting our time

vast vessel
#

oh nooo

#

thats just a break point

vast vessel
verbal dome
#

So setting sharedMaterials on a Visual Effect causes a crash?

vast vessel
#

yes

#

i dont even know why we are allowed to do that, that should be handled by the visual effect component

lofty vault
#

I asked this earlier and deleted cause I thought I fixed it but apparently not.
I am trying to do a simple data save to json and I keep getting UnauthorizedAccessException. Could it be because I am calling it from the OnDestroy function of an EditorWindow class?
This is the code:

path = "/Assignment_03/Data/BoardData.json";
string directory = Application.dataPath + path;
System.IO.File.WriteAllText(directory, jsonObject);
keen dew
#

dataPath is read only. Typically you'd save data to persistentDataPath

lofty vault
#

Same issue

keen dew
#

and use Path.Join to build the directory

languid spire
lofty vault
#

Combine is for some reason only returnig the path string

languid spire
lofty vault
#
string directory = System.IO.Path.Combine(Application.persistentDataPath, path);
Debug.Log(directory); //prints "/Assignment_03/Data/BoardData.json"
still pond
#

I get the following error: Assets\Scripts\Quiz.cs(88,15): error CS1061: 'Timer' does not contain a definition for 'CancelTimer' and no accessible extension method 'CancelTimer' accepting a first argument of type 'Timer' could be found (are you missing a using directive or an assembly reference?). I have a reference to a timer object in my quiz script that calls the public function "CancelTimer" from the timer object, I have no errors in the code but the error from above pops up in unity.

languid spire
lofty vault
#

Ah, alright. Thanks!

cosmic dagger
eternal falconBOT
still pond
eager spindle
#

its most likely because you didnt save the file, attach to unity has nothing to do with that problem

#

you need to save all your code files so stuff like that doesnt happen

still pond
#

i did save multiple times using ctrs+s

eager spindle
#

but like you need to save all the files

still pond
#

oh ok. thanks

eager spindle
#

e.g. I can use TechTalkManager in ActivateOnEnter in my code, visual studio says its ok but because I havent saved TechTalkManager yet unity will yell at me

#

because of the *

lofty vault
winged seal
#

why does it say this

#

im new to unity

eager spindle
winged seal
#

it wont launch

eager spindle
#

but its because you have a different version of unity

winged seal
#

i been waiting for the past hour

eager spindle
#

oh like it gets stuck on loading?

#

you can task manager end it

winged seal
#

no it wont EVEN LOAD ANYTHING

#

it just says this i click continue 10 mins go by nothing

eager spindle
#

yea end the thing in task manager and try launching it again

winged seal
#

okay

#

ok i saw something it was the unity's logo and it had a red alert next to it

#

for a split sec

#

let me try to screenshot it at the time

#

there it is

eager spindle
#

oh thats a crash message

#

unity crashed

winged seal
#

omg

eager spindle
#

that ! also appears when you run unity games

#

you can only task manager end it

#

or restart your pc

winged seal
#

okay

#

okay im back it still keeps crashing

languid spire
#

can you screenshot of the contents of the project folder you are trying to open

winged seal
#

Alright.

#

you mean the file or in unity?

languid spire
#

I mean the folder using File Explorer

winged seal
languid spire
#

OK. Delete the Library and Temp folders and try to open the project again

winged seal
#

need a restart or not?

languid spire
#

no

winged seal
#

ok

#

ok now it's on the loading screen

#

yipee

#

ok its done loading do i need to wait?

languid spire
#

wait? Is the Editor not open?

winged seal
#

nope

languid spire
#

screenshot your task bar

winged seal
#

1 sec

#

in task manager too right?

#

it dropped an error when i started it again

languid spire
#

no, windows task bar

winged seal
#

huh

#

there it is

winged seal
#

there right?

#

thats in task bar

languid spire
#

that is NOT the task bar

winged seal
#

holy pupu im dumb

#

you mean here

#

if no idk

eager spindle
#

press ctrl shift esc

languid spire
#

no, not that either. May I suggest you spend some time to learn how to use your computer

eager spindle
#

task manager

#

search bar on top: end everything with unity

winged seal
#

thats all with unity

eager spindle
#

i guess you can end unity hub too

#

if it has unity as a subprocess

eager spindle
#

once you end the task go delete the library fiiles too

#

and try again

#

how did you even get a project to corrupt like this where is it from

winged seal
#

I just downloaded unity and it just said this

hexed terrace
#

and threaded

winged seal
#

ok

eager spindle
#

in the standard rp, whats the difference between using a shader on the camera versus applying a shader to all objects? im not really sure how shaders work

#

i wanted to make a rolling world shader like animal crossing, the shader that I have only applies it to objects though

hexed terrace
#

you don't put shaders on the camera, are you getting confused with post processing?

eager spindle
#

whats the difference between post processing and applying a shader to all objects

#

idk how I can apply my shader to all my assets reliably

#

i did see setreplacementshader and was thinking if I should switch to standard rp(my project is currently on URP)

quaint flicker
#

Hey, can you give me some high level architectural tips? (I suffer from analysis paralysis, and would like someone to just give me some pointers to get me going). I'm struggling to add a serialized inventory, so I can load a save game and have an item in hand if I last saved with it in hand. (I have items on my levels that I can pickup (which assigns them to an "inHand" var on the pickup behaviour for example). So when I load my state and reset the player, do I just set all of my state? or call the code for pickup (so "simulating" picking up the item again?) Also My item is loaded as part of a level, when I load a gamestate on a different level, I need to also somehow load that one item to put it in my character's hand)

eager spindle
# quaint flicker Hey, can you give me some high level architectural tips? (I suffer from analysis...

im not sure how your inventory works, but if we take minecraft for example every slot is assigned a number. and the inHand variable would be the slot number

you could use your pickup code when loading in items but if theres any items with "on pickup" passives that could cause issues. again we dont know what your pickup code has so we cant give an answer.

overall theres not enough information here to advise you on this.

rocky canyon
quaint flicker
# eager spindle im not sure how your inventory works, but if we take minecraft for example every...

imagine I have nothing, I learn as I go, so I'm willing to scrap any solution I made that's not really "how things are done". So currently, an item is just a model with a script on the level, and when the character picks it up, that same prefab model is moved and parented to the character's hand. which made sense, but now when I'm getting to the inventory / serialization part I see it would probably make more sense to have some "db" (or scripted object) of items where an item type would have a separate prefab for something that's spawned on the level, and another representation for being in hand (like in an fps / or minecraft the onscreen in hand models are totally different from their in world representations)

verbal dome
eager spindle
#

ive spent a lot of time trying to make a custom render pass but it somehow doesnt work out

verbal dome
#

It was pretty easy in HDRP but URP seems a bit more complex

rocky canyon
#

its not too bad but there are a couple of steps

pine bone
#

Hello, im making a custom level editor in my game and i have some questions. Currently i can edit position, rotation and scale values of objects when i click on them but i want to add custom parameters for specific types of objects .For example when i click on a vehicle it should show a speed value that can be editable, an explosive object should display explosion force and damage. Whats the best way of doing this without making spaghetti code?

eager spindle
#

the last time I made an editor for it, it was spaghetti code. you can make a serialisable class and loop through the variables depending on the available variables

pine bone
fading seal
#

how can i get this code to work in the game (i have a main menu scene and it works in that but not the level scene)

rocky canyon
#

i'd probably use a base class w/ ur standard parameters.. and maybe a dictionary that u can override for custom properties.. and then derive from that class for all ur different types

#
public abstract class EditableObject
{
    public Vector3 Position { get; set; }
    public Quaternion Rotation { get; set; }
    public Vector3 Scale { get; set; }

    public abstract Dictionary<string, object> GetCustomParameters();
    public abstract void SetCustomParameter(string key, object value);
}``` something like this perhaps?
```cs
public class Vehicle : EditableObject```
```cs
public class Explosive : EditableObject```
eager spindle
pine bone
eager spindle
#

yea

eager spindle
eager spindle
#

like drag and drop it in

rocky canyon
#
    public override void SetCustomParameter(string key, object value)
    {
        if (key == "ExplosionForce") ExplosionForce = (float)value;
        if (key == "Damage") Damage = (float)value;
    }```
eager spindle
#

🎊

fading seal
pine bone
#

can it take any type of value?

rocky canyon
#

pretty much

eager spindle
rocky canyon
#

theres probably a better way.. but im just learning how to use inheritance.. so im trying to up my game

eager spindle
#

very fun thing: you can use typeof function

#

and other ways to get type

rocky canyon
pine bone
rocky canyon
#

i would Not copy and paste any of my code.. i can't help u expand on it lol

#

just giving u an idea of what u can try

eager spindle
#

pseudo code but something like this can be done

class Shape;
class Circle : Shape;
class Square : Shape;

Circle shape = new();
switch(shape) {
  case Circle _circle:
    ...
  case Square _square:
    ...
}

this checks what type the shape is, then you can use it accordingly

#

so if its a Circle, you can use _circle
if its a Square, use _square

rocky canyon
#

ya, its still gonna be a chunky system if u have multiple things u want to be able to change

eager spindle
#

also see:

if(shape is Circle _circle) {
  ...
}```
pine bone
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class EditableObject
{
    public Vector3 Position { get; set; }
    public Quaternion Rotation { get; set; }
    public Vector3 Scale { get; set; }

    public abstract Dictionary<string, object> GetCustomParameters();
    public abstract void SetCustomParameter(string key, object value);
}

I want to use this code, is there a way to add it in objects and edit it in the editor

eager spindle
swift crag
#

Note that using is often indicates that you have a design problem

eager spindle
pine bone
swift crag
#

indicating that you should be adding a virtual method to the parent class and moving the logic in there

#

It does makes sense for "bag of data" classes, I suppose

willow scroll
pine bone
rocky canyon
#

and derive from thatpublic class Vehicle : EditableObject and put that on the gameobject

eager spindle
rocky canyon
#

maybe someone else like ^ this can help better.. b/c i haven't implemented anything like this before

#

im just spitballing

pine bone
#

the speed variable will be edited in build mode

#

and when the game runs the plane script checks if it has a variable

fading seal
#

does anyone know any extentions to make coding easier in vs code?

pine bone
#

and then changes its own variable

rocky canyon
#

u could yes.. if it was a basic Monobehaviour

eager spindle
#

found this online but not very good: typeof(Class).GetProperties();

rocky canyon
#

ignore the PlatformIO

fading seal
eager spindle
#

thereafter you can loop through the properties of the class

#

so let's say you want to loop through Explosive: foreach(var property in typeof(Explosive).GetProperties())

#

theres definitely better ways to do it

rocky canyon
#

always is lol

pine bone
rocky canyon
#

i like structs

eager spindle
#

well what are you going to do with property now

#

oh

#

yea that works actually

pine bone
eager spindle
#

but now you're stuck to int

rocky canyon
#

ya, he could use it for anything he wanted if hes working only w/ int values

late burrow
#

can i make something like interface but in array fashion

eager spindle
late burrow
#

so i can [i] for my custom type to get something

pine bone
eager spindle
pine bone
#

oh i forgot lol

eager spindle
#

but youll have to get its type later anyway which loops back to the casting problem brought up earlier

#

it works for now though

rocky canyon
#

cuz thats weird.. lol i'd have to look into that myself

late burrow
#

huh no idea i just want non array to act as array

#

where i can [i] to get custom thing

#

from my custom class

rocky canyon
#

whats the purpose?

late burrow
#

getting data from class

eager spindle
#
public class thing {
  public string this[int key] {
    //... return a string
  }
}

note that you have to use this, the name of the key and the name of the class can be anything

rocky canyon
#

why not use a dictionary

#

and get ur data w/ keys

rocky canyon
late burrow
#

arrayless array yes that what i wanted

eager spindle
#

actually yea its a dict

#

you can return any property though

rocky canyon
#

ahh cool okay

eager spindle
#

its like a gettersetter for dict

pine bone
rocky canyon
#

makes sense

eager spindle
#

loops back to the original problem

pine bone
#

why

eager spindle
#

you store everything as strings, lets say you have an Explosive class with the property of range. range is an int so you need to cast from string to int. also how would you restrict input to only allow int to be entered

polar acorn
late burrow
#

why you complain about everything

rocky canyon
#

im also curious

eager spindle
polar acorn
eager spindle
#

thats the only thing I can draw from this

polar acorn
#

Arrays exist. Use them.

late burrow
#

because by the years you sitting here you know my options are limited

eager spindle
polar acorn
eager spindle
#

c# doesnt have "arrayless arrays" or whatever youre bringing up

rocky canyon
#

ya, most things said are actually in good faith..

swift crag
eager spindle
#

do provide a code example

swift crag
#

this is either some completely insane VRChat thing or someone trying to reverse-engineer a game

eager spindle
#

or someone that came from knockoff programming language that tries to re-invent the wheel

polar acorn
#

Like, what gives you access to creating custom classes but can't have arrays? What let's you make enum flags but can't use the << operator?

burnt vapor
#

Beginner chat never fails to amaze me

eager spindle
#

even if its not from any programming language just type it out

#

we will see what we can do

late burrow
polar acorn
#

If you're going to come here and say "I can't do the obvious solution to my problem" then you're 100% going to need to explain why otherwise the problem has been solved

burnt vapor
swift crag
#

make a god-damn array, so help me god

eager spindle
# late burrow i got answer here so i already dont ask for more

ill expand on this: ```public class BetterDict
{
public Dictionary<string, string> _data = new Dictionary<string, string>();

    public string this[string key]
    {
        get
        {
            if (!_data.ContainsKey(key))
            {
                _data[key] = string.Empty;
            }
            return _data[key];
        }
        set
        {
            _data[key] = value;
        }

    }

    public float GetFloat(string key)
    {
        if (this[key] == "")
        {
            this[key] = "0";
            return 0;
        }
        if (float.TryParse(this[key], out float swag))
        {
            return swag;
        }
        else
        {
            this[key] = "0";
            return 0;
        }
    }

}

this dict behaves like the one in js where it returns an empty string if theres nothing there
pine bone
eager spindle
#

i shouldve pasted this but yea

pine bone
#

i could change it later if i want to add other values

polar acorn
#

It's been, what, a month? And you still haven't explained why you can't just use a goddamn list

eager spindle
burnt vapor
eager spindle
#

yep

burnt vapor
#

Like, just store it as an object if you are doing this

eager spindle
#

im just lazy

burnt vapor
#

Alright

eager spindle
#

i need to write it to a file too

#

i love storing my savefile in plain text

cosmic dagger
#

quick question: i have a one-time event listener class. is it worth to have a separate field for a single callback or easier to just assign the single callback to the collection and remove the private System.Action _callback; field?
https://hatebin.com/qzjhjlgjpd

pine bone
#

thanks for helping @eager spindle @rocky canyon

rocky canyon
eager spindle
#

even the docs define it like this

swift crag
swift crag
#

Iterating over a one-element list is going to be marginally more expensive

#

and I'd rather not have to fuss over different behavior for one vs. many callbacks

shell sorrel
#

why is a list needed, you can add many callbacks to 1 Action

swift crag
#

it makes garbage

cosmic dagger
eager spindle
swift crag
shell sorrel
#

depending on what point you want the args baked in, you can just bake it in via a lambda with no args

swift crag
#

you can't meaningfully invoke anything other than a System.Action if you're responding to an event that passes no arguments

swift crag
shell sorrel
#

can only really menually handle args if you know them up front or can bake them into a new delegate

swift crag
#

since adding elements to or removing elements from a list will break the enumerator

cosmic dagger
dense plume
#

If you are wanting a listener to only fire a method once on an event, why not just unsubscribe from the event on the listener side when it's called?

swift crag
#
action += anotherAction;

This produces an entirely new action that has nothing to do with the old one, so it can be safely done in the middle of the action being invoked

shell sorrel
#

whats the intended end goal?

#

you just want a event that invokes then removes

dense plume
#

Yeah the listener can unsub from the event in the callback method i dont get writing this big wrapper

shell sorrel
#

yeah if i want a invoke once, just unsub on invoke

swift crag
#

i wonder if an anonymous function can still unsubscribe itself

shell sorrel
cosmic dagger
shell sorrel
#

you can define a named function inside a function

dense plume
swift crag
#

rather than having to copy-paste logic everywhere

#

and yes, this is impossible

shell sorrel
#

Also to handle args you will need a bunch of generic variants for each amount of args

eager spindle
#

stupid method though

shell sorrel
swift crag
swift crag
#

I don't understand why everyone is clamoring to come up with a workaround. I think this is perfectly reasonable

shell sorrel
#

like if you want to unsub ofcourse it needs a way to indentify just it

cosmic dagger
# dense plume Yeah the listener can unsub from the event in the callback method i dont get wri...

@shell sorrel yeah, this was the original extension method i had . . .

// Both params are closures
public static UnityEvent OneTimeEvent(this UnityEvent unityEvent, Action callback)
{
    // Delegate allocation
    unityEvent.AddListener(Invoke);
    return unityEvent;

    void Invoke()
    {
        // Delegate allocation
        unityEvent.RemoveListener(Invoke);
        callback.Invoke();
    }
}

it works fine, but both params become closures and adding/removing the named function creates a new delegate instance every time. i wanted to try and avoid this. so it's a separate (wrapper) class . . .

swift crag
#

I do something similar with an event that's meant to be re-subscribed to every time it's fired

#

in that case, though, the event just gets set to null after being invoked

swift crag
# rocky canyon why is this?

because I had a situation where multiple places in my code wanted to hear about the next time a specific thing happens

dense plume
#

Im really curious about the use case now

swift crag
#

I forget where I did this, actually. I'll have to go dig it up

#

(this indicates how non-remarkable the idea is 😛 )

#

It's identical to a List<System.Action> that gets cleared after the invocation (assuming you don't try to add/remove callbacks in the middle of the invocation)

#

Another place I use something similar is a "debug drawer" class

#

I want to be able to draw gizmos from anywhere in my code

#

not just OnDrawGizmos or OnDrawGizmosSelected

#

but you obviously can't draw gizmos outside of those messages

#

so I have a singleton that you stuff actions into, which then get executed at the right moment

#

the list gets cleared every frame

open gull
#

I have a mechanic in mind, but I don't know exactly how I can run it.
It would be something like time travel, when I press the button, the scenario changes to 2, when I press it again, it goes back to scenario 1.
Is there any way to do this without loading, just using a transition?
I'd have to create another scene for this, or I can make it so that such objects don't render until I press the button, and after I press it again, other objects render and others stop? (I don't know if this should be in this chat or in the game design chat srry)
is a 2d project

dense plume
#

Oh make rendering layers

#

Swap to a camera that has those layers or change the layers on your camera in code

open gull
dense plume
#

Inspector shows it as culling mask on the camera

eager spindle
#

for context its here

#

see the bottom

#

rendering->culling mask

dense plume
#

Thanks for that

open gull
#

It worked exactly as I was thinking, thanks!

dense plume
rocky canyon
swift crag
#

unity offers this kind of thing in EditorApplication

stuck palm
#

why cant i do this?

eager spindle
#

what is GameState

swift crag
#

If that's a struct, I don't think you get equality out of the box

stuck palm
swift crag
#

I would go ahead and implement IEquatable<GameState>

#

Then implement operator == and operator !=

swift crag
#

(or, more generally, check if two simulations of the game are in sync)

stuck palm
swift crag
eager spindle
#

structs are immutable, you're comparing the value of the struct.
lets say you have ```struct ObjStruct {
int x, y, z;
}
class ObjClass {
int x, y, z;
}


assuming you use an operator overide, comparing ObjStruct against an ObjStruct checks if the values x, y and z are the same. if you have two different structs with the same values, this will return true,

comparing ObjClass checks if they're the same object. if you have two different objects with the same values, this will return false.
swift crag
#

yeah, the default equality test for reference types is to compare the references themselves

stuck palm
#

added the operators as rider suggested

eager spindle
#

lets say you have

ObjStruct first = new();
ObjStruct second = first;

seccond is a copy of first. doing ```
second.x = 1

will not change `first`.

but if you do the same thing with`ObjClass`, then both `first` and `second` will change because you are modifying the same object
eager spindle
swift crag
eager spindle
#

do you need it to be a struct?

swift crag
#

then have Equals compare ComputeHash() and other.ComputeHash()

#

(this way, ComputeHash can return an int or a long or whatever the heck you want it to)

#

GetHashCode can call ComputeHash and then turn it into an int, if needed

stuck palm
eager spindle
#

when I first learned about the difference in how struct vs object is treated in c++ vs c# i was appalled

swift crag
#

it's not like all of its members are value types

#

It's got two List<Vector3>s

stuck palm
swift crag
#

The default equality check for reference types is to compare references

#

You can override this.

stuck palm
# swift crag You can override this.

okay. how does this look for a computehash method btw

public Hash128 ComputeHash()
    {
        Hash128 newHash = new Hash128();
        newHash.Append(playerPositions);
        newHash.Append(playerVelocities);
        return newHash;
    }
fading seal
#

what do i add to the code to make it whenever the light flickers the bulb goes black?

eager spindle
swift crag
fading seal
swift crag
#

So that would work.

eager spindle
#

this thing

#

you should look up the docs on Light

#

or you can right click Light and go to definition

swift crag
#

Do you have a model of the lightbulb?

fading seal
swift crag
fading seal
swift crag
#

Grim is asking about changing the visual look of a model, it sounds like

swift crag
#

Drag the MeshRenderer for the light into it

#

You can now do bulbRenderer.material.color = Color.black, or whatever you want

fading seal
swift crag
#

Renderer.material is the first material used by the Renderer, and Material.color is the main color of the Material.

swift crag
#

but you'll do something like that

fading seal
swift crag
#

otherwise you'd be modifying the original material object (which might be used by many different renderers)

fading seal
fading seal
swift crag
#

[SerializeField] Renderer bulbRenderer;

#

this will hold a Renderer

fading seal
#

oh ok

fading seal
gilded kiln
#

Hi, how can I move the centre with the blue circle?

rocky canyon
fading seal
swift crag
#

You probably want to do that in Flashing instead

swift crag
swift crag
#

In the top right corner of the material's inspector, there's a "..." menu that lets you select the shader

swift crag
gilded kiln
swift crag
swift crag
#

Compare that to when you enable and disable the light.

gilded kiln
swift crag
#

Right. You change the color at the same time that you enable or disable the light.

#

Now you're going to need to set the emission color property, instead of just .color

#

you'll use SetColor for this

#

e.g. material.SetColor("SomeColorProperty", Color.white);

#

You should do two things:

  • Pick the correct color, based on whether the light is enabled or disabled
  • Set the emission to that color
#

This would be a smart place to use a conditional operator

#
Color emission = testLight.enabled ? Color.white : Color.black;
#

If the light is enabled, you get white. If the light is disabled, you get black.

fading seal
swift crag
#

well, where do you need the color?

fading seal
#

in flashing right?

rocky canyon
#

might need a conditional as well..

    material.color = Color.black;
else
    material.color = Color.white;```
#

after u toggle the light ofc

swift crag
rocky canyon
#

aok

rocky canyon
#

ternary.. so simple i dont notice it half the time 😄

swift crag
#

its proper name is the "conditional operator"

#

it is a ternary, but that's a bit like calling + the binary operator 😁

fading seal
rocky canyon
swift crag
rocky canyon
#

may be AI 😉

swift crag
#

bulbRenderer.material.SetColor will set a color property on the material

#

that's the Intellicode doohickey

#

or Codeium

#

too many things

rocky canyon
#

codeium yea

fading seal
swift crag
rocky canyon
#

i love codeium, u give it some variables.. and a decent script name and it damn near writes it for you

swift crag
#

If you see an _EmissionColor property in the list, you're good to go.

fading seal
#

so do i type the grey stuff?

rocky canyon
#

u can press tab and it will fill it in for u

fading seal
#

@swift crag and @rocky canyon you guys are amazing tysm for the help it actually made sense lol

terse plume
#

its been a looong time but... do we still need to cache this.transform or unity got smart enough to not do a GetComponent each time?

rocky canyon
#

no need to cache a transform.. imo unless u just want to

hexed terrace
#

I've never cached it

rocky canyon
#

i used to.. b/c i thought it was cool t.GetComponent<>

terse plume
#

does this.transform still do GetComponent<Transform>? 🤔

rocky canyon
#

no

#

it caches it internally

hexed terrace
#

I'd be surprised if it ever has

rocky canyon
#

id be disappointed if it did

hexed terrace
#

Although, I suppose I shouldn't be .. after all there was Camera.Main

fading seal
hexed terrace
#

!code

eternal falconBOT
rocky canyon
#

the bottom part ^

hexed terrace
#

same as CS, but with a single `

rocky canyon
#

the back ticks are usually next to ur 1 key

hexed terrace
#

on both sides..

rocky canyon
#

nope.. thats a quotation mark

#

its the ~ key above ur tab button

solar arrow
#

how to get children reference in unity toolkit?

hexed terrace
#

you have to tell it where to start and end

rocky canyon
#

like this

fading seal
solar arrow
rocky canyon
#

it'll block smaller messages b/c it thinks its spam

fading seal
rocky canyon
#

ya thats spam 😛

fading seal
#

mb

#

test

hexed terrace
fading seal
#

yayy

rocky canyon
#

aye!

#

and to doo big blocks u use three on both sides

#
public class CachingExample : MonoBehaviour
{
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>(); // Cache the Rigidbody component
    }

    void Update()
    {
        rb.AddForce(Vector3.up); // Use the cached component
    }
}```
fading seal
rocky canyon
#

nah, sorry but im here everyday 👍

solar arrow
#

m_NPCTextDialogue = uIDocument.rootVisualElement.Q<VisualElement>("NPCDialogue").Q<VisualElement>().Q<Label>();

can someone help me why this code doesnt work?
i tried to get a label reference here

rocky canyon
#

i also have a YT channel if u wanna check that out

fading seal
rocky canyon
#

sure i dont mind

fading seal
#

ok ty

fading seal
rocky canyon
#

same as my name

fading seal
#

ok

rocky canyon
#

its also in my profile

fading seal
rocky canyon
#

any errors in ur console?

solar arrow
rocky canyon
#

if its not working i'd debug each part of it until u make it thru the end

#

and see if u get any null reference errors

solar arrow
#

im tripping rn

#

now it works

rocky canyon
#

ahah! magic 🪄

solar arrow
#

i didnt change anything

rocky canyon
#

did ur Editor recompile before u tested?

#

maybe it just lagging a bit

solar arrow
rocky canyon
#

sometimes if its been open a while it'll get lazy

#

i have to tab in and out sometimes to force it to recompile my code changes

#

a restart normally speeds it back up

solar arrow
#

ah man

#

it works when i change the tab to discord and change it back to unity

rocky canyon
#

just learned that myself 🙂

solar arrow
#

thanks for the info dude

fading seal
#

@rocky canyon how would i add a sound to the lamp whenever it flicks on?

rocky canyon
#

add an audiosource to it.. put a clip into it.. and when u flick it on and off you can

audioSourceReference.Play();```
rocky canyon
#

or you can reference an audio clip in the script and leave the audio source slot blank.. and then use audioSourceReference.PlayOneShot(audioClipReference);

rocky canyon
#

looks good to me... as long as ur reference is assigned 👍

rocky canyon
rocky canyon
#

you'll want to put it in ur Coroutine.. like u did the material change

rocky canyon
#

or whenever u trigger the light (however you do that)

fading seal
rocky canyon
#

ahh okay.. sooo when it flickers u should call that

rocky canyon
#

yup

fading seal
#

ok lemme test it

rocky canyon
#

the reason I use Stop() before i Play.. is that it keeps audio clips from overlapping

#

sometimes they can sound weird

#

and make sure ur audiosource isn't set to Looping

fading seal
fading seal
rocky canyon
#

and.. it might be obvious.. but dont put the audiosource on the object ur turning on and off

#

b/c once u turn it off the audio source will go off too

fading seal
rocky canyon
#

anything that doesn't get turned off

#

even an empty gameobject.. just depends on how u wanna do it

fading seal
fading seal
rocky canyon
#

nope no audio

fading seal
fading seal
fading seal
rocky canyon
fading seal
#

alr

rocky canyon
#

had to test it myself..

#

works fine here..

#
    IEnumerator FlickerLightAndAudio()
    {
        while (true)
        {
            flickeringLight.enabled = !flickeringLight.enabled;

            if (audioSource.isPlaying)
                audioSource.Stop();
            else
                audioSource.Play();

            yield return new WaitForSeconds(1f);
        }
    }```
willow scroll
rocky canyon
#

maybe try the if/ else statment to see if that helps

fading seal
rocky canyon
#

it gets overrun

willow scroll
#

This just scared me

rocky canyon
#

heres my real one.. its a bit better

ionic zephyr
#

why isnt it stacking items?

willow scroll
rocky canyon
#

indeed 😉

hexed terrace
rocky canyon
#

phuck ya

#

super big class

willow scroll
#

Still I'm not sure why there are 3 scenes in Assets if there's the "Scenes" folder

rocky canyon
#

haven't gotten around to organizing it again... i do it like once a few weeks

ionic zephyr
rocky canyon
#

trust me.. the internal folders are very organized

gaunt ice
ionic zephyr
#

Collections of struct

willow scroll
rocky canyon
#

im aware.. and i structure my projects as i please..

#

can u concern urself w/ something else?

willow scroll
#

Sure.

rocky canyon
#

thank you

fading seal
#

@rocky canyon its working but its only playing when its off. and i only want it to play when its on

rocky canyon
fading seal
#

i think i know whats wrong

rocky canyon
#

if(light is enabled) -> stop and play

#

else (dont do it)

gaunt ice
# ionic zephyr Collections of struct

to array() copies all the "values" (whole struct or pointer if it is class) from your collection (no idea what it is) and you are modify the copied value in the return array (ie access the struct in the returned array), but the original struct in the collections wont be modified
quite hard to explain it in plain text

fading seal
ionic zephyr
#

so maybe I should make it a class?

fading seal
gaunt ice
#

what is your collection?
you should not call toarray every iteration

ionic zephyr
fading seal
#

@rocky canyon i want the buzzing to play when the light is on / white

gaunt ice
#

then you can modify the struct in list by copy->change its field->assign it back

your_struct the_struct=list[i];
the_struct.field=value;
list[i]=the_struct;
rocky canyon
ionic zephyr
rocky canyon
# fading seal ok ill try

orr if its a buzzing loop that ur using

if(testLight.enabled){
flickerSound.Play();
}else{
flickerSound.Stop();
}```
#

if light is on -> Play() if light is off -> Stop()

gaunt ice
#

probably if the struct is "large" (Microsoft says large==greater than 16 bytes)

rocky canyon
#

no problem! i didn't know it was a buzzing noise or i'd mentioned that earlier

#

i thought it was like a click on/off sound

fading seal
rocky canyon
#

mmhmm.. always name ur stuff appropriately.. it helps u find stuff quickly..

#

and u dont want people like Sashok randomly complaining about ur project folder

fading seal
fading seal
swift crag
#

record MP4s

hexed terrace
#

keep it on topic too, this is a code chan

rocky canyon
gloomy nebula
#
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

public class PipeSpawnScript : MonoBehaviour
{
    public GameObject pipe;
    public float spawnRate = 2;
    public float destroyRate = 4;
    private float timer = 0;

    // Start is called before the first frame update
    void Start()
    {
        spawnPipe();
    }

    // Update is called once per frame
    void Update()
    {
         if (timer < spawnRate)
         {
            timer = timer + Time.deltaTime;
         } else
         {
            spawnPipe();
            timer = 0;

         }
    }

    void spawnPipe()
    {
        Instantiate(pipe, transform.position, transform.rotation);
        Destroy(pipe, destroyRate);
        
    }
}

any reason for this to not destroy the pipes? im making a flappy bird game, trying to use the Destroy function to destroy the pipes after a certain time delay, but im just getting an error instead.

rocky canyon
#

looks like ur trying to destroy the prefab

#

and not the Instance (copy) that u spawned

fading seal
gloomy nebula
rocky canyon
#

you are trying to destroy the prefab

#

you cant do that

gloomy nebula
hexed terrace
#

follow the tutorial and it'll tell ya ;p

rocky canyon
#

you need to cache them when u create them

fading seal
rich adder
#

the copy is the "instance" in this case

rocky canyon
#

var copy = Instantiate(prefab);
Destroy(copy, 3f);

rich adder
#

how I get myself not confused

  public GameObject pipe; // bad name
  public GameObject pipePrefab; // goodname
fading seal
rocky canyon
#

camelCase public variables 😦

wintry quarry
#

public variables 😢

fading seal
rich adder
rocky canyon
vale bronze
#

Are there any good videos on how to write good / production quality code in unity? i've been working on a game for about two weeks and it going decently well, but I am noticing that my code is messy and I would like to bring any further code I make cleaner.

hexed terrace
#

add the cs so it's colour coded

wintry quarry
rocky canyon
#

💯 as a beginnner just get stuff to work

#

worry about that stuff later

fading seal
rocky canyon
#

u have to skip a line

vale bronze
rich adder
#

yeah right if it works, as long its not an unmaintainable mess

hexed terrace
vale bronze
#

like dont get me wrong, some of my code is good and I proud of it, but other parts look 💀

swift crag
#

I don't think a video will help you to write "better" code

#

experience will, though

rocky canyon
#

and make sure theres no spaces after it

hexed terrace
rocky canyon
#

he figured it out

vale bronze
#

thanks for the pdf :)

rocky canyon
#

i found it comes with experience more than anything.. once u have to start refactoring b/c u can't keep track of whats happening.. thats when u start to learn what works for you and how to write things neater

rich adder
fading seal
rocky canyon
#

i have never tested my code on another machine... i bet 20% of it doesnt work

swift crag
#

I test my game mostly on my macbook. I also run it on my Steam Deck (and even sometimes on my PC!)

ionic zephyr
#

My player objects are stored in a List of a class called ItemAmount(objects hat contain the item data and its quantity). Is it better that every time my Inventory updates(receives an object/releases an object) I build it from scratch by using the items and quantities in the List or just updating the objects that were changed

rocky canyon
swift crag
#

i've discovered some really weird platform-specific issues

#

all of my IMGUI text was just...gone on my steam deck

#

the font didn't work

rocky canyon
#

ohh dear lord.. i havent even started experimenting w/ cross platforms

#

😢

rocky canyon
ionic zephyr
#

I haven´t tryed it yet

ionic zephyr
dense plume
rocky canyon
#

sounds lovely lol

swift crag
#

most of my platform-dependent code is for stuff like opening a file browser

rocky canyon
#

why not run a windows virtual machine? @dense plume

swift crag
#

and for correctly displaying the command icon instead of the windows logo on macos

#

Unity handles almost everything for you.

dense plume
rocky canyon
#

as long as it works

#

i cant stand linux

swift crag
#

It's actually concerning if you have something that only works on one platform

rocky canyon
#

i'd be super suprised if my projects didnt work on other platforms..

#

but work perfectly nah.. most likely not

ionic zephyr
#

What I am doing is reseting all the slots in the inventory every time it is updated and then showing the "abstract" inventory

rocky canyon
#

im sure stuff lik eu mentioned.. UI

#

UI would probably be the culprit

rocky canyon
ionic zephyr
#

its just I thought reseting the inventory every time it is updated sounds awful in terms of efficiency

#

Is it common to do so?

ionic zephyr
ionic zephyr
dense plume
#

My first go at "UI slots" would probably be a dictionary tbh, each slot being the key with inventory items as values

rich adder
#

like a logic representation of the UI ?

ionic zephyr
rich adder
#

weird name but seems fine

ionic zephyr
dense plume
#

Class? without methods you might consider a struct

ionic zephyr
dense plume
#

Ahh so this is like, "Arrows" as an item, with some mutable quantity, like a consumable

dense plume
#

I agree with navarone that this class would probably be more readable as just "InventoryItem" or somesuch, but hey if you understand it, that's good

#

So you're storing these ItemAmount classes in some list for the UI to display?

ionic zephyr
dense plume
#

Try a dictionary

#

So you'll know what item is in a particular slot

rich adder
#

Dictionaries are dope, wish Unity could out the box serialize them. But alas we need to do magic tricks with struct 😛

dense plume
#

Sounds like you'll also need a "UISlot" class to handle interaction and reference the UI elements

rich adder
#

thats what I do. Mine usually goes

-InventoryManager
-UISlotsManager
-UISlot