#archived-code-general

1 messages · Page 440 of 1

shadow wagon
#

would be a pretty basic programming exercise, its dead simple, very little complexity to it. and the level of skill it takes, is something where if you had the technical ability to a game, youd have the relavent skills to make fizzbuzz

safe fable
#

im using networking for MP so its different kind of

#

but same logic basically

lean sail
#

thats doesnt even use the same method they're asking about..

safe fable
sage heart
#

i got message

#

fk yall

#

monsters

#

devils

safe fable
#

why are u so upset mannn

#

its not that deep

sage heart
#

my hentai pic:((

lean sail
vagrant blade
sage heart
safe fable
#

ok.

mossy flare
#

You have to be 13 to use Discord.

sage heart
#

thanks god

vagrant blade
#

Anyway, just going to ban you anyway. See ya.

shadow wagon
#

pour one out

vagrant blade
#

!ban save 1245773585436377210 Spam. Racism.

tawny elkBOT
#

dynoSuccess imnotdifferent. was banned.

safe fable
#

that was... bizarre to say the least

dense pasture
#

frigging kids just have no idea how to do anything themselves anymore

safe fable
#

fictional character lol

dense pasture
#

like actually bloody helpless

lean sail
#

One thing Id suggest is also just printing out the velocity and seeing how it changes over time too. Maybe along with the current time

#

@safe fable @shadow wagon @dense pasture theres nothing you need to say about it. really just move on. most of the conversation above shouldve been avoided

shadow wagon
dense pasture
#

thats even more mind blowing

#

when i got into coding i had to beg my mom to get me all these 50lb books on C and BASIC

#

and thats the only way you had to learn it

#

trial and error

mossy flare
dense pasture
#

like all the resources we got available today are insane

safe fable
dense pasture
#

if you dont understand it, yeah dont use ai.

#

if you've been doing this for almost 30 years, i'm just tired of rewriting all the boilerplate crap

lean sail
#

If you all want to DM each other then go ahead, but again theres no off topic in the channels. This is seriously just spam and it's really hard to help the person actually asking for help!

safe fable
#

sorry you're right

dense pasture
#

anyway, back to it

shadow wagon
#

also before when barely anyone was making gamedev resources, or online knowledge was limited, that was basically a forced "yall gonna have to figure this all out yourself"

lean sail
safe fable
dense pasture
#

(they're real sticklers about categorizing your discussions)

mossy flare
#

unity discord members when somebody strays from the channel topic for 0.0001 seconds

night harness
#

Actually a fair point the channel name is a little unideal

lean sail
shadow wagon
#

now theres a million tutorials for making an inventory and because you have to gamify youtube that means the most low tier garabge "illusion of being educational" tutorials are everywhere

lean sail
lean sail
night harness
dense pasture
#

👀

#

i'm not gonna troll you you're helpful

safe fable
night harness
#

It’s not a discord power tripping thing it’s just a respect to the insane amount of volunteered support taking place

dense pasture
#

kid came in and disrupted that himself lol

#

anyway, its over. back to work! all of you

lean sail
# mossy flare Here is the issue more clearly

honestly its hard to tell what im looking at, I meant it more as debug and see for yourself what the values were over time. Ideally just move in 1 direction too so the vector is easy to read (or print out the magnitude).
You'd still need to share the context surrounding the one line you pasted. Theres a lot more than just calling Smoothdamp, like how are you even using that Velocity

#

one thing that was concerning was the walk speed being 0.01 also

#

Plus there were so many messages between the beginning and now I can barely find the other messages

mossy flare
#

If it's anything above 0.01 the character zooms off. No idea why this is the case.

lean sail
#

well just assigning the velocity vector doesnt move the character in the first place. share the whole relevant code

mossy flare
lean sail
#

!code

tawny elkBOT
shadow wagon
#

discord just puts posts over 2000 chars into a message.txt

lean sail
shadow wagon
#

oh yeah, ignore me 😆

lean sail
# mossy flare

is there a reason also you're using Smoothdamp here on the velocity anyways? Id really just use MoveTowards here, as I suggested the other day
you are moving by velocity every frame also cc.Move(velocity); rather than every second so you should use Time.deltaTime. This is what i meant when i said "Theres a lot more than just calling Smoothdamp, like how are you even using that Velocity"

#

that is why your walk speed is currently very low

safe fable
#

anyone here have any experience with using Steamworks.NET?

Its not a big issue (yet) but for some reason when I play my game, steam will not recongnize when i close the game and always keep it running. (or rather say its running), until i close it in task manager.

#

fixed the console issue btw @somber nacelle 😄

#

it was just a bunch of anchor issues and transform issues ... just tideous stuff

#

also i do make sure run in background is disabled

somber nacelle
safe fable
#

@somber nacelle sorry i should have worded myself better. it persists even when its standalone

somber nacelle
#

or do you mean that the actual build is still running? because that is something else entirely most likely

safe fable
#

yeah unforuntately the actual build it still happens

somber nacelle
#

if you're certain it is related to steamworks.net then find their support channels and get help with it there

safe fable
#

Yeah, thats definitely probably the best bet

#

thanks

steady bobcat
#

fyi do not disable this option for multiplayer games as if you tab out bye bye connection (rust used to do this)

steady bobcat
steady bobcat
#

i presume its only the main thread updating that is "paused"

safe fable
#

everytime i alt tab and idle for a bit my character disconnects from the server

#

so we'll see

#

@steady bobcat yeah that actually just fixed an issue that i was having that i blew off. I thought it was something to do with photon fusion causing a disconnect after a certain amount of inactivity

#

turns out that was the issue

#

you fixed a problem for me i didn't even ask 🥲 ❤️

steady bobcat
#

haha glad to have helped

old elk
#

so i've gotta ask, how am i supposed to get around the C# reflection cache exactly if i'm using reflection to find and construct serializers/converters? it seems silly that I can't disable the cache

#

i can't seem to find any information on why this is done in the first place

#

Mono and IL2CPP internally cache all C# reflection (System.Reflection) objects and by design, Unity doesn’t garbage collect them.
0 explanation for why this is by design

#

ah, buried in the bowels of google

craggy jewel
#

Could someone help me? I've been beating my head against the wall trying to get some udon# scripts to work but I can't seem to

#

Like it won't turn the script into the udon#

leaden ice
tawny elkBOT
leaden ice
#

you'll find the most VRChat expertise here^

craggy jewel
#

alright, thanks man

zinc flax
#

is creating meshes instead of tilemaps in unity possible?

#

tag me if someone has an answer

thin aurora
pulsar plinth
#

I've heard instantiating 2 or more assets at the same time can make the game stutter
is Unity that sensitive to asset instantiation?

lean sail
thin aurora
#

Which can be fixed by itself by implementing some simple asynchronous delegation

west lotus
#

We have built in async Instansiate now

stable osprey
#

@west lotus So spawning 1m elements won’t spike?

fallen drift
# pulsar plinth I've heard instantiating 2 or more assets at the same time can make the game stu...

It takes resources to instantiate or destroy objects. But that isn't a sensitivity issue on Unity's side but more of a fact of how things work. It will take resources on your PC to open any program, or create any file.

It's also important to understand what a "stutter" is. Your game's smoothness relies on the application updating constantly. Each update cycle is called a "frame." That's where fps, or frames per second, come into play.

Movies are normally shot at 24fps, TV shows at 30, and fast moving competitive games at 60+.

A stutter is when a frame takes longer than it should to process and the average fps drops because of it.

So yes, you can cause a stutter by instantiating or destroying too many objects within the same frame. But there are tons of techniques to handle that.

fallen drift
stable osprey
#

They mentioned built in async, makes me wonder

pulsar plinth
steady bobcat
#

Something something async is not always using other threads

fallen drift
somber nacelle
#

plain c# async is also not inherently multithreading

west lotus
pulsar plinth
#

well, I'll certainly have to come up with something to smoothen instance creation, since rooms may have like 50 enemies in it all occasionally instancing projectiles

west lotus
#

Projectiles should be pooled

stable osprey
#

Makes sense.. async but instantiation still has to complete within the frame

pulsar plinth
west lotus
#

Google object pooling

fallen drift
pulsar plinth
stable osprey
pulsar plinth
#

I can't postpone instantiation because my game has to be frame perfect

#

but I can pull other tricks

stable osprey
lean sail
pulsar plinth
#

that makes sense

#

I mean, it did the short to teach what object pooling is

#

the enemy in question threw 8 projectiles in a single blow

#

perhaps I just phrased it badly

lean sail
#

8 projectiles probably shouldnt stutter in the first place, but do yourself a favor and just look at the docs for unitys object pool. It's very easy to implement

pulsar plinth
#

I see
thanks there

thin aurora
#

Well yeah so I didn't clarify on what to do specifically because of that. You can do the process asynchronously if you can afford doing it, but it's not as simple as spawning a background thread. You can also use some other asynchronous methods. Maybe even introduce pooling.

wraith cobalt
#

I wanna see the game engine (or operating system for that matter) that doesn't spike when you perform an extremely expensive operation.

sinful hull
#

I'm trying to implement accelerometer for my 3d bounce ball game. I can't seem to move much in horizontal direction using accelerometer. Below is my script. I have tried google and chatgpt etc as well but can't seem to resolve this.

https://paste.myst.rs/gqm6cu65

mellow sigil
#

The code uses horizontal acceleration as is but adds the vertical acceleration to the existing velocity

woeful hamlet
#

I have collectibles using an Event that contains their type (an enum) and position (Vector3), but not every Listener cares about both of those. Is there a way to add a Listener that automatically discards one or both parameters, or do I have to add them to the signature of every function I want to listen to the Event?

rigid island
#

is no big deal

#

unless you make a signature without those

leaden ice
#

You can ignore them with the _ discard syntax though

woeful hamlet
leaden ice
#

you write _ instead of the parameter name/type

woeful hamlet
#

public void DoStuff(CollectibleType _, Vector3 __)
Like this?

leaden ice
#

depends on the context. For a regular method, yes.
For a lambda, you don't need the type either

lean sail
leaden ice
#

Oh interesting. TIL _ in a regular method is just a variable name.

lean sail
#

it does hint I guess that the variable is not used, i dont think ive ever used it in such a way though. It's funny that this is valid

void MyMethod(int _)
{
  _ = 5;    
}
#

no more single character variable names, we move onto underscores

woeful hamlet
#

It's a regular method. Using the underscore does prevent my compiler from complaining about unused variables, though.

low hinge
#

Should be using longer descriptive variable names anyhow, imo

naive swallow
lean sail
#

Unless the subscribing method doesnt care about any variable at all

low hinge
lean sail
low hinge
#

Went right over my head

safe fable
#

hey guys, are we able to upload unity projects to github. Is there any problem with that? only reason im asking is because i know they have their own version control thing but from what i see its like $200/m 😄

But is there any issues with just uploading to github for collab and version control?

#

i guess im more concered over file sizes and stuff if git supports that

leaden ice
#

from what i see its like $200/m
just like GitHub, Unity has a free tier within certain limits.

safe fable
#

@leaden ice got it. Surely i would need the LFS thing git offers, since the project is 2+GB?

leaden ice
#

LFS is about the size of individual files

#

not the size of the repo

#

You should use LFS in general, yes.

safe fable
#

i see i see

wide totem
#

Hey guys, I wanted to know if you think im overthinking what im trying to do. I am trying to make a script that can read a list of components with assigned values (7 components, each with 15 possible values) and create an object out of it (the object is a 'spell', but not really relevant to what im trying to do rn). Each value in the components may also have modifyable 'values', like dimensions for the square value under the shape catagory.
Would the best way to go about doing this be an Interface for each category, with each value being a class(? i dont know what instances of interfaces are called) of the its catagories interface, with the Interface having all the possible modifiable subvalues?

wide totem
# leaden ice can you give some examples?

yeah, sorry this is kinda hard to explain.
A heat ball spell:
Category - Magic Type: Value - Heat
Category - Target: Value - Projectile
Category - Source: Value - (Character Object)
Category - Shape: Value - Circle: Subvalue - Dimensions: Vector2 (2,2)
Category - Duration: Value - Until Collision
Category - Intent: Value - Projectile: Subvalue - Speed_Intesity_Ratio: Vector2 (30,70)
Category - Cost: Value - Set_Amount: Subvalue - Amount: int 30

#

each category would have an indiviual interface

#

each value of that category would have a script under that interface

#

and the interface would have all the possible subvalues for the main values contained under it

brave geyser
#

What benefit is having each unique class have its own unique interface?

leaden ice
wide totem
leaden ice
# wide totem yeah, sorry this is kinda hard to explain. A heat ball spell: Category - Magic T...

The way I'm doing it in my current project is something like:

public class Spell {
  List<Attribute> attributes;
}

public class Attribute {
  double _value;
  AttributeType type;
}

public enum AttributeType {
  MagicType,
  Shape,
  Duration,
  Cost,
  // etc...
}
``` source and target wouldn't be part of this object, but maybe some other object that wraps the spell with a source and target for casting.
#

And I use various encoding schemes with the double value to encode various types of data in it

#

it works with all these data types: int, float, Vector2, and custom enums

wide totem
#

im a bit confused, ill look at the code for a little bit and see if i understand ✅

leaden ice
#

Later on i might add more stuff to support other types if needed

brave geyser
wide totem
brave geyser
#

Seems a little odd to have the interface have properties you don't want in all of the classes that use it. Normally an interface is a good way to ensure any class that uses it has all of its properties or methods available.

somber nacelle
#

in fact, you can't not implement an interface's members so that code isn't valid

leaden ice
#

Yeah this is definitely not a use case for interfaces

wide totem
leaden ice
#

The only thing that's an enum in that link is AttributeType

wide totem
#

oops yeah thats what i meant

leaden ice
#

For an individual spell or something you would have a List<Attribute>

#

conceptually just like your example above

#

Category - Magic Type: Value - Heat
Category - Target: Value - Projectile
Category - Source: Value - (Character Object)
Category - Shape: Value - Circle: Subvalue - Dimensions: Vector2 (2,2)
Category - Duration: Value - Until Collision
Category - Intent: Value - Projectile: Subvalue - Speed_Intesity_Ratio: Vector2 (30,70)
Category - Cost: Value - Set_Amount: Subvalue - Amount: int 30

#

Each line here would be one attribute

#

except as I mentiuoned above I don't think Source and Target belong in this list

wide totem
#

what does editorDisplayTypes do?

#

oh nvm i see it

leaden ice
#

Here's an example.
Attributes is an AttributeList, and there are two Attributes in this particular list

#

It lets me display them properly in the editor

#

So the Loyalty attribute displays as the Loyalty enum value dropdown.
Hull Integrity displays as an int

wide totem
#
return editorDisplayTypes.GetValueOrDefault(type, typeof(double)); // Default to double (for now)

just returns the first instance of a double type in attributes right?

leaden ice
#

no

#

it returns the value mapped to type in the Dictionary

#

and if it doesn't find one, it returns typeof(double)

wide totem
#

oh i see

leaden ice
#

basically just saying double is the default

#

I haven't shared everything here - there are missing pieces like the AttributeList class and the editor scripts

#

Just trying to give you a gist for how I'm doing things in this project.

wide totem
#

Okay i think i get the idea of it

leaden ice
#

Essentially it's just a list of tags and values

#

and I'm just using a little trickery to shove all the different value types into a single double field - but that part isn't even necessary

#

you could do this same thing by giving attribute several fields like public int intValue, float floatValue, Vector2 vector2Value etc and your code should know based on context which one is appropriate to use for a given tag.

#

It would waste a bit of memory that way though

wide totem
#

thank you for the help! Im gonna give it a try

somber nacelle
uneven patrol
#

hi, just wondering is there any method to run code only if under a specific build profile? like a preprocessor define or something

leaden ice
#

Build profiles let you define scripting defines

tough carbon
#

Rider stucks if it haven't updated code, but game is already running. "Don't start game before update" isn't solution, because I don't want after кandom click restart unity

#

Is there way prewent unity from running if files are updating or another solution?

steady bobcat
zinc parrot
#

so in HDRP, with unity lights, if I do Light.type, why is Point the same value as Area(rectangle)?
It means that according to LightType, Rectangle and Point are the exact same(but Disk and Point are NOT)

tropic steppe
#

is it a good standard to impliment a standard system via prefabs? ie if im going to have NPCs in my game have nametags i have a nametag prefab that i toss on each npc? and if im going to have a proximity prompt interact thing (ie press E to interact once within a trigger box) id have that on a prefab too?

leaden ice
tropic steppe
#

also how do i make my game effecient... like if im going to have a decently sized nice quality map id need to optemise it to actually run it, i know this means like model culling and like unrendering but when should i be thinking about that? what should i do as a standard, and should i make scripts to do thoes optimal things from the start?

#

i know id avoid heavy processes, huge triangle counts, and other unnessicary considerations in final graphics setup and stuff, but like... are there any programming techniques i need to know/avoid?

steady moat
tropic steppe
#

whats that?

steady moat
#

You can hold only a certain amount of assets in memory.

#

If you have huge map with a lot of variety, you might easily bust RAM.

#

Obviously, it depends on what you have for assets.

#

Low Poly is usually not an issue.

tropic steppe
#

yea however i wouldnt need the entire map to be simulated/rendered at once... so i presume id just pause processees... (processi?) in the far off areas to handle many many assets

steady moat
#

Do you know what RAM is ?

tropic steppe
#

yes

#

ive done comp sci but am new to unity and C#

steady moat
#

Do you understand that each assets take space in RAM.

tropic steppe
#

yes, but if you have a chunk 15x the render distance out you dont need that in ram, so youd unload it.

#

remove from ram

steady moat
#

If you have 1000 textures 4k, but only 200 are actually used in a section of the map, you are wasting resources.

#

The process of unloading and loading assets is asset streaming.

#

You cannot simply deactivate it.

steady moat
#

You need to use things like additive scene or/and addressable to handle that.

#

But again, it is only an issue if you believe you are going to get to that point in term of assets.

tropic steppe
#

i think i will

#

i plan to have a quite expansive map with some town areas you travel between, so a lot of space will be dedicated to lush expanses with a ton of models scattered around, using lower poly versions at further distances will help ease that, but there still might be thousands of individual models on screen at once

steady moat
#

If your map is in space or have 5km+, you might want to use floating origin as well.

#

That being said, you should try to restrict yourself to something small. Authoring everything would be extremely hard alone.

tropic steppe
#

i can get something rough put together relatively quickly, plus the in between landscape doesnt have to be perfectly refined straight away so im thinking of getting it there and down before making it look nicer

cold parrot
#

Also mind that the unity editor does not support working on large detailed maps efficiently. It will be a painfully slow experience for authoring.

#

you can work around that but for a solo project, that wasted effort is virtually never worth it vs spending it on other, more valuable bits of the project.

tropic steppe
#

yea i was thinking of having areas like open feilds or dense forests have the common foliage put in during loading, bcs theyd all be clones anyway so i can just set up a script to place so many randomly within set areas, so my actual workspace map will be much less detailed than what is there during actual play.

cold parrot
#

if you can’t fit your game into 4km square and avoid streaming that map. You should investigate other engines.

fleet gorge
#

unreal engine is geared towards bigger worlds and does a lot of the optimisation for you. you could replicate the same systems in unity if you know how to

cold parrot
#

you can get streaming to work quite easily, but that’s not the same as having a good workflow too.

tropic steppe
#

well ive asked because i wasnt going to have a super super detailed like photorealistic map, but i wanted it to span a long distance

cold parrot
#

photorealism isn’t even the issue here

tropic steppe
#

i know city skylines is so bad bcs its using something in its graphics that is very heavy in how theyre using it, but i was wondering if i could like have a map that can look nice with a decent level of detail that does span quite a long distance

#

like if it in runtime handles that

cold parrot
#

The rendering is not the issue

#

Memory is, as was mentioned

tropic steppe
#

bcs i have methods i could use to circumvent the editor space not liking super high asset numbers, and in runtime asset streaming can remove nearly all the assets to keep the RAM useage low

#

well... manageable

cold parrot
#

You can have a huge map if you only want to look at it from far away. It’s all a function of perspective

cold parrot
tropic steppe
#

i mean like, if i had a forest that you can at a realistic speed walk around in, 1:1 scale, and i wanted an hour long walk in one direction (5 miles) where it is a nice somewhat detailed setting at each moment. that would simply be too many assets for the editor, however if i generate thoes assets and make use of asset streaming to cull the stuff too far away thatd be fine in runtime wouldnt it?

tropic steppe
cold parrot
#

I think you still haven’t fully understood what exactly the critical parameters are

cosmic rain
#

Just because you have millions of trees doesn't mean that you consume 1 tree worth * million of RAM. That would make most open world games impossible.

#

You also seem to confuse culling with asset streaming. Culling is preventing objects from rendering. Streaming is loading/unloading them into/out of memory.

uneven patrol
astral sky
#

https://docs.unity3d.com/6000.0/Documentation/Manual/json-serialization.html
Is the JSON serializer good? According to the manual's own page it's better and faster than "popular json tools" which I assume they mean Newtonsoft as I've heard a couple of horror stories from that. Idea is to serialize most if not all data driven game data into json and read off it at runtime, then probably turn into blob assets

leaden ice
tropic steppe
# cosmic rain Just because you have millions of trees doesn't mean that you consume 1 tree wor...

yea, so for this i would use asset streaming to unload items too far away and handle the ram requirement,
then i would use culling, draw call batching, instancing, LODs, Billboards to reduce strain on the gpu from rendering the scene,
would i need to do anything else to make a scene too large to be simultaneously all loaded actually workable? like do i need to worry about editor limits too much?

#

im thinking i can have each asset normally be a cube to prevent undue stress in the editor from detailed models, and have scripts turn the models into what's required in the start-up process... should the editor struggle with showing all of the assets

night harness
#

If your editor can’t handle it you probably should consider changing what game you are making

cosmic rain
#

Because it sounds like you're trying to fix a problem that doesn't exist yet.

outer karma
#

Hi guys! Idk if this is the correct spot but I have a question I am trying to create a script where an enemy follows the player around a maze. Does anyone have a good tutorial or reference I can follow?

latent latch
outer karma
#

Thank you guys!!

low arrow
#

How do i figure out what names Animation.Play() is expecting?

#

This is my current setup in editor

vestal arch
low arrow
#

Yeah

#

but this is my current setup, and it's saying "OpenOptions" doesnt exist when i callTitleScreen.OpenOptions()

using System;
using UnityEngine;

public class TitleScreen : MonoBehaviour
{
    [Header("Parts")]
    [SerializeField] private Animation animations;
    [Header("State")]
    [SerializeField] private bool buttonsFrozen = false;

    private void Start()
    {
        animations = GetComponent<Animation>();
        print(animations.GetClipCount());
    }

    public void QuitGame()
    {
        if (buttonsFrozen) return;

        Application.Quit();
        print("Quit game");
    }

    public void OpenOptions()
    {
        if (buttonsFrozen) return;

        animations.Play("OpenOptions");
    }
    public void CloseOptions()
    {
        if (buttonsFrozen) return;

        animations.Play("CloseOptions");
    }

    public void PlayLevel()
    {
        if (buttonsFrozen) return;

        print("Play level");
    }

    public void FreezeButtons()
    {
        buttonsFrozen = true;
    }

    public void UnfreezeButtons()
    {
        buttonsFrozen = false;
    }
}
#

It does say it has 2 animation clips, but i can't get any more info

vestal arch
low arrow
#

Ohhh

#

Probably not...?

vestal arch
#

Animations must be marked as ‘Legacy’ in the Inspector for the animations to be found by this method. This option appears after switching the Inspector Window to ‘Debug’.

#

new AnimationClips are for Animator, legacy AnimationClips are for Animation

low arrow
#

OH

#

found it

#

i have never seen this before, alright

wide totem
#

is there a way for me to make a custom curved collider? using polygonal works in base, but when scaled up, the vertexs get less and less accurate. im trying to make a cone collider

#

and using a capsul collider to approximate has the same issues

leaden ice
#

by providing a custom mesh.

wide totem
#

i see, ill look into it. ty

pastel patio
#

Hi guys, I've trying to figure out how to use a package called ModTool, but I haven't been able to get it to work whatsoever- I don't really know why and documentations on ModTool is scarce to the extend that I can't find any info...
For the reason in case this becomes an XY question, I've been trying to figure how to add support for additional content (Including code) to my game

lean sail
pastel patio
#

They only have a thread on discussions.unity.com, 1 outdated tutorial, and a documentation that doesn't explain my issues

lean sail
pastel patio
#

It's actually mainly about myself, since I'd like to take a more modular approach to the kind of content that exists, if users wanna mod it why not, but I'd like to be capable of just messing around and spam random stuff, players can include the optional content if they want to

#

Partially it's also because otherwise I feel restricted when it comes to the "cannon" content

#

Might be viable to make MonoBehaviours for modded content that reference ScriptableObjects containing Lua code like you suggested (or something similar)... But will prefer to use it as a secondary solution, since I'm pretty sure that it'll still put a lot of restrictions...

lean sail
languid vessel
#

Hey, how do ya'll deal with "double namespaces" in Rider (I suppose it should be similar with just resharper)?

For example, I have an asmdef with the following root namespace: MyCompany.MyGame.Runtime. Then I place a script in the following folder: Assets/Scripts/Runtime/MyScript.cs. Then, Rider complains that namespace MyCompany.MyGame.Runtime is incorrect and should be MyCompany.MyGame.Runtime.Runtime.

I know I can exclude namespace providers/folders via right click and saving this info to .DotSettings, however am curious if there are other ways around this as I don't like to litter my repos with these files.

fleet gorge
#

I don't use rider but I could guess that you can use just one .DotSettings file and provide the full path to the script?

faint viper
#

not sure if this is the right place to ask, but my AI boss character spins around like a bey-blade, and also pretty often falls through the floor

i am following a quite long tutorial series -- the boss is using a navmesh agent aswell as a character controller and a rigid body, not sure where to begin with the troubleshooting

languid vessel
#

The .DotSettings files are created for each .csproj file when you exclude a namespace provider it seems (there are more cases where they are useful tho), I don't think you can have a single file 🤔

The contents of this file don't seem to include any mentions of the asmdef itself

<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=assets_005Cscripts_005Ccore/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

The problem is not the files themselves, but that I have too many of them since we use asmdef extensively 😅 This is esp annoying for custom packages, a bit nitpicky but I want clean repos!

rocky pumice
#

In many projects I need some way to permanently store data such as "current gold" or "levels completed". Many objects in different scenes need to access this data. For a long time now, I've been using DataManagers with a script like this. And then other objects could access the DataManager via FindObjectOfType(). However this doesn't feel like the best solution so I was wondering if there was a better alternative?

(Its especially annoying, that I cant use FindObjectOfType<DataManager> in a Start function and instead always need to have some short delay before trying to acess the DataManager)

steady moat
fallen drift
steady moat
#

Alternatively, you could dependency injection as well.

rocky pumice
#

Thanks! I will look into that

shadow wagon
#
public static class DataManager
{
  public static int GoldCollected;
  public static int LevelsWon;
}```you could also do a very basic static class like this
#

anywhere you want to access it, its as simple as DataManager.GoldCollected

#

beauty is you never need to create an instance of the class beforehand, it always exists

rocky pumice
#

thats really cool

lean sail
# rocky pumice thats really cool

its not really recommended to use static like this unless you're really sure its what you want. what you had above was already the singleton pattern so its confusing why you use FindObjectOfType in the first place.

rocky pumice
#

I see. I'll look more into singletons then

lean sail
vestal arch
rocky pumice
vestal arch
rocky pumice
#

Thanks!

somber tapir
#

Is there an easy way to rename scripts (and their references) in a local package? When I use VS rename function the change doesn't "stick".

steady bobcat
velvet falcon
#

I've been trying to position a gameobject on the left edge of my camera (a pixel perfect camera, I might add) through code, but the size of the "game" pannel in the editor changes the values of both Screen.width and Camera.main.pixelWidth.
Is is a bug? How should I obtain this data instead?

steady bobcat
#

Use the pixel width/height of the camera as Screen reports incorrectly in editor

#

I've also noticed Screen report different values randomly in editor so I gave up using it

velvet falcon
steady bobcat
#

are you sure? Its correct for me and often Screen reports my monitor resolution instead.

#

Anyway you could just do viewport -> world pos

velvet falcon
vestal arch
steady bobcat
#

viewport is 0,0 -> 1,1 so you can get a corner in world space easier

vestal arch
#

since you're changing the viewport, and the height of the camera (in world space) is what stays consistent

vestal arch
velvet falcon
vestal arch
#

then what rob said, yeah

#

alternatively, you could get the world-space halfwidth (camera.orthographicsize * camera.aspectratio) and offset your game object from the camera by that (perhaps minus half the width of the gameobject/its sprite if you want it to left-align)

unkempt meadow
#

Unity is fucking with my mind. My player is constantly triggering an "on trigger stay" from an object that's miles away...and disabled!

#

I went through everything, and it always triggers, all the time

#

I just can't understand why that would happen

#

is this just a hopeless bug?

leaden ice
unkempt meadow
#

Will do

#

Had to go out for a frustration cigarette

#

!code

tawny elkBOT
unkempt meadow
#
 private void OnTriggerStay(Collider other)
    {
        if (other.CompareTag("crawl") && !FlashlightRotation.flashlightOn)
        {
            Debug.Log(other.gameObject.name);
            controller.radius = 0.05f;
            controller.height = 0.2f;
            controller.center = new Vector3(0, 0.63f, 0.57f);
            if(!enteredWithFlashlight)
            {
                EnterCrawl();
            }
        }
            }
unkempt meadow
leaden ice
#

alright... and the rest? WHich script is this code part of? Which object is the script attached to? What other components are on the objects? Where are the objects located in the scene?

#

What is getting logged in the console?

unkempt meadow
#

as for the script, this is the line that is triggering, I would think the rest is irrelevant

#

the triggered object is logged

#

I mean I can show the screenshot of the empty object but it's miles away AND disabled

leaden ice
#

show screenshots of all the obejcts involvedc

#

including their inspectors

#

and a screenshot of the console logs being printed

leaden ice
unkempt meadow
#

I mean ok

#

this is my player with the new test terrain

#

selected is the object which triggers the on trigger stay

#

you can't see it, but it's very far away

#

and also disabled

leaden ice
#

looks like it's right here, no?

unkempt meadow
#

the player is the one with the script, triggering thestay

#

no it's not

#

different angle:

#

it's like hundreds of meters away

#

but that shouldn't be a factor, as the object is disabled

leaden ice
#

and hwo do we know it's this object anyway

#

I'd also like to see any and all colliders on the player

#

It would be better to see the screenshots during playmode too, while the logs are printing

unkempt meadow
#

so I fixed it by disabling the collider on that object, on top of disabling the object itself

#

that has got to be a bug

leaden ice
#

in so many words

#

Basically I'm just going through the motions of debugging

#

don't take it personally

unkempt meadow
#

This is what it was before I disabled the colliders

#

sorry no, that's a new log, now functional

#

OK so, when I disable the object, it always triggers it, regardless of proximity

#

when I enable it, it works properly

#

only god knows how that happens

leaden ice
#

if you can reproduce it, submit as a bug

unkempt meadow
#

aand now it's also triggering it when not touching when it's on

#

I don't know man

#

this is now interaction with a new, closer trigger

#

And here's the player collider

leaden ice
unkempt meadow
#

See, now it's even further away

unkempt meadow
leaden ice
unkempt meadow
leaden ice
#

The "include layers" thing you have there will include those layers in addition to whatever is in the collision matrix in the physics settings

unkempt meadow
#

aha

leaden ice
#

It additionally includes player model

unkempt meadow
#

so it should exclude everything but the player model

leaden ice
#

Probably

#

you could also use the layer collision matrix in physics settings

unkempt meadow
#

I will try but not feeling positive

rocky jackal
#

I have a UI manager that manages what menu is currently open and all that stuff but I have some issues since I added these UnityEvents into the menu class, the events randomly stop working and then when I restart unity or enter play mode enough times they just fix themselves. How can I make events for each menu without getting all these bugs from serialisation issues ?

leaden ice
unkempt meadow
# leaden ice Probably

nope, doesn't work...one thing, it only happens when I turn off the flashlight and it always happens when I turn it off, because only then is it qualified to collide

#

but there is nothing in that flashlight script that references anything of the sort

rocky jackal
# leaden ice Wdym by them randomly stop working?

Well one moment im in playmode and everything works perfectly fine, I spam all the buttons I try to break the events and it works but then when I re enter playmode and i carefully do a single action that triggers one of the OnMenuOpen events and it just completley breaks telling me that the target of the UnityEvent went missing eventho its still there

leaden ice
rocky jackal
#

This is the menu class

[Serializable]
public class menu
{
    public string name;
    public List<GameObject> menuObject = new List<GameObject>();
    public Camera camera;
    public string parentMenu;
    public InputActionReference shortcut;

    public UnityEvent OnMenuOpen = new UnityEvent();
    public UnityEvent OnMenuClose = new UnityEvent();

    [HideInInspector] private bool currentState = false;

    public void ChangeState(bool state)
    {
        // only do events when the state actually changed
        if (state != currentState)
        {
            // invoke corresponding evens
            if (state == false)
            {
                OnMenuClose.Invoke();
            }
            else if (OnMenuOpen != null)
            {
                OnMenuOpen.Invoke();
            }
        }

        // change the state of all the menu objects
        foreach (GameObject obj in menuObject)
        {
            obj.SetActive(state);
        }

        currentState = state;
    }
}```
leaden ice
#

!code

tawny elkBOT
rocky jackal
leaden ice
#

alright and - again what's the exact full error message you're receiving?

rocky jackal
#

Gimme a second, it only happens randomly

#

theres multiple errors

leaden ice
#

scroll down until you find the first error

#

click on it so you can see the expanded full error message underneat

#

copy and paste that expanded full message here.

rocky jackal
#

ObjectDisposedException: SerializedProperty lastOpenMenu.OnMenuOpen.m_PersistentCalls.m_Calls.Array.data[0].m_Target has disappeared!
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <8ad9ecbe25e14b10b6dde783af6e4aa2>:0)

leaden ice
#

ok that one is just an editor bug

#

next haha

rocky jackal
#

InvalidOperationException: The operation is not possible when moved past all properties (Next returned false)
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <da771086bc2e4cfc9ad0a72e083a7f98>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <e66f217a64a747d48b478f0d70978704>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <8ad9ecbe25e14b10b6dde783af6e4aa2>:0)

leaden ice
#

probably this one is what we want I guess

rocky jackal
#

NullReferenceException: Object reference not set to an instance of an object
InventoryManager.OpenMainInventory () (at Assets/Code/Inventory/InventoryManager.cs:115)
UnityEngine.Events.InvokableCall.Invoke () (at <17484a9af6b944dea5cd9be4dbb0da2c>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <17484a9af6b944dea5cd9be4dbb0da2c>:0)
menu.ChangeState (System.Boolean state) (at Assets/Code/UI/UIManager.cs:162)
UIManager.OpenMenu (System.String name) (at Assets/Code/UI/UIManager.cs:62)
UIManager.Update () (at Assets/Code/UI/UIManager.cs:38)

leaden ice
#

Ok so it's happening in InventoryManager.cs line 115

rocky jackal
#

thats this line

#

but I only get this specific error when all the other errors happen aswell

leaden ice
#

SO looks like either primaryOpenInventory is null or UIManager.instance is null or UIManager.instance.lastOpenMenu is null

#

I would add some Debug.Log right above that to find out which one is null

#

or attach a debugger there

#

based on this trace it looks like the unity event part is working fine

#

it's just an error inside the listener itself

rocky jackal
#

Im pretty sure its the UIManager.instance.lastOpenMenu

leaden ice
#

yes but it's possible that third one will throw an NRE itself. In which case - we'll at least know what the problem is.

rocky jackal
#

I have a different problem, it fixed itself again and I cant reproduce the error anymore

leaden ice
#

probably some kind of timing or race condition issue then

#

Although

#

Was it happening only when the inspector was open before?

#

Maybe reopen the inspector if you closed it?

rocky jackal
rocky jackal
#

what should I do now, if the last open Inventory is null idont want to trigger the return function

leaden ice
#

What should happen if it's null?

rocky jackal
#

I want the open inventory function to continue as usual

leaden ice
#
var lastOpenMenu = UIManager.instance.lastOpenMenu;
if (!primaryOpenInventory.solo || (lastOpenMenu != null && lastOpenMenu.camera != null)) {
  return;
}```
#

something like this

zinc parrot
#

TRU thanks, forgot about that
deleting so its not a double post

reef garnet
#

Quick simple question, is there an attribute to grey out properties as shown above, the example was done with a custom property drawer, I just want to do it for a value that is only there for display purposes, greying it to clearly show that

reef garnet
#

simply out, if it exists what would GreyOutAttribute be in this example usage [SerializeField, GreyOutAttribute] private float currentSpeed;

#

ah ok

fallen drift
leaden ice
reef garnet
#

thought read only doesn't serialize

leaden ice
#

that's what I meant to linik^

reef garnet
leaden ice
#

NuaghtyAttributes REadonly doesn't affect serialization

fallen drift
reef garnet
#

fair enough, was only for display purposes, thanks for the quick response

patent perch
#

Hi
I want to dragf & drop MonoBehaviour (components) from my inspector to a var
How I can do this?
Thx

leaden ice
patent perch
#

I don't have Transform or GameObject, MonoBehaviour with interface like this -> MonoBehaviour, IBossAttackPattern
I can't drag & drop my component into this public List<Component> patternScript = new List<Component>(); or replace with MonoBehaviour

rigid island
#

are you dragging instances of those MB ?

#

or are you dragging the textfile / textasset

patent perch
rigid island
# patent perch

are there some type of custom constraints on those fields ?

patent perch
#

What do u mean?
I have this :
public List<MonoBehaviour> patternScript = new List<MonoBehaviour>();

And BossManager:
public List<BossPhase> Phases = new List<BossPhase>();

patent perch
#

public List<MonoBehaviour> patternScript = new List<MonoBehaviour>();

rigid island
#

so there are no custom attributes or anything ?

patent perch
#

It might be because its a SO?

rigid island
#

ahh

#

I gotta recall how it handles scene components, I think that might be the issue

patent perch
#

It was the problem

rigid island
#

yeah that makes sense now

#

what threw me off a bit is the inspector showed what was inside the SO in the list? i dont recall doing it by default no?

#

is there a custom inspector / property drawer there or am I just misremembering?

patent perch
#

I use NaughtyAttributes which add a lot of attributes like showing the SO in inspector

rigid island
#

ahh ok makes sense, normally it would in a struct / class

lament bear
#

in Unity 6 getcomponents gets the components of a certain type in the order they are in the inspector or is their order not reliable?

somber nacelle
#

pretty sure order is not guaranteed

#

if you need a specific order for some reason you should instead use a serialized field for the array and assign them manually

lament bear
somber nacelle
vestal arch
lament bear
#

@somber nacelle But how can I assign them in an array in the order they are in the inspector with/without getcomponents if getcomponents are not reliable?

somber nacelle
vestal arch
#

arrays are ordered, you would just put them in the array in the order that you want them

somber nacelle
#

damnit discord won't copy the message link

lament bear
#

because getcomponents are not reliable right

somber nacelle
#

surely you know how to read, yes?

vestal arch
#

we aren't telling you to use getcomponents

lament bear
somber nacelle
#

assign 👏 them 👏 in 👏 the 👏 inspector 👏

lament bear
somber nacelle
#

what is the actual purpose of doing this

#

because at this point, this is turning into an XY Problem

lament bear
#

Because all the components are of the same type and on the same object

somber nacelle
#

that does not answer the question i asked

vestal arch
#

what are you trying to make

lament bear
#

So there's no way I can drag them into the public array because they are in the same object.

somber nacelle
#

yes there is, just lock the inspector or open the properties for the component with the array and drag the components in individually instead of the entire gameobject. but you've still not bothered actually answering what the actual purpose of doing this is

lament bear
#

I'm doing each system in separate scripts, and I want to run each function in a specific order if necessary, for example the player controller.

#

It's a noob question

lament bear
somber nacelle
rocky pumice
#

hey, so I've heard using public variables is bad and using get and set like this is better. How do I get them to apear in the inspector now? [SerializeField] doesn't seem to work.

somber nacelle
#

for auto properties you can target the compiler generated backing field for attributes using the field: attribute target like [field: SerializeField]

latent latch
#

public setters are usually frowned upon if it's not meant to be changed from outside of the class, but public getters are usually fine for any case

rocky pumice
#

thanks!

latent latch
#

regardless, you're doing a public set get there so nothing really changes

#
public float Horizontal { get; private set; }

Is the idea you're probably looking for

#
[field: SerializeField] public float Horizontal { get; private set; }```
rocky pumice
#

I actually do want to change the varibles from another script here

latent latch
#

In that case just making a public variable is fine without the auto property

somber nacelle
#

although technically the property is better in case you decide you want to change anything about getting/setting the value later on (such as adding validation code)

rocky pumice
#

I see, yeah that makes sense

neat tundra
#

Anyone happen to know why my fill (on a horizontally filled image) is not working properly with this function?

private void UpdateCountLabel(int newValue) {
    ammoCountLabel.text = $"{newValue} / {maxMagCount.Value}";
    fill.fillAmount = currentMagCount.Value / maxMagCount.Value;
}

when currentMagCount.Value is 10, maxMagCount.Value is 12, it should be setting it to like 0.83, but instead its being set to 0, no matter what. Setting the label works, so the function it self is called when its needed to be called... so I'm quite confused

somber nacelle
#

int divided by int results in an int

steady bobcat
#

int/int strikes again

neat tundra
#

but its a float..

somber nacelle
#

which value is the float

#

because newValue is an int and it sounds like maxMagCount.Value is also an int

neat tundra
#

hold on

#

let me see

somber nacelle
#

just because the variable that holds the result is a float does not mean that the actual result of the math is a float. 10 / 12 is 0 because they are both integers. but 10 / 12f or 10f / 12 is 0.83f

neat tundra
#

ok so that is indeed the case, I see

somber nacelle
#

cast one of the values to float and it will work the way you want it to

neat tundra
#

i just set(float)maxMagCount.value and its working

#

Thanks a bunch, I was trying to figure this out for like 30 minutes.

steady bobcat
#

in Visual studio you can hover and see the op it will use which can help in future

neat tundra
#

Ah I see, thanks!

old linden
#

Can anyone spot why my Angle method is returning the opposing sign I would expect? The values are correct, just not the sign.

private float GetAngle(Transform hotspotTransform)
        {
            Vector3 targetDir = hotspotTransform.position - firstPersonTR.transform.position;
            targetDir.y = firstPersonTR.transform.position.y;
            Debug.Log($"Angle for {hotspotTransform.name}: {targetDir}, {Vector3.SignedAngle(targetDir, firstPersonTR.transform.forward, Vector3.up)}");
            return Vector3.SignedAngle(targetDir, firstPersonTR.transform.forward, Vector3.up);
        }
#

The Object with the Video graphic is Hotspot 3, I should mention. The selected object is the firstPersonTR transform in the method

low arrow
#

Also! How do i make one screen space overlay canvas render on top of another screen space overlay canvas?

#

(they're from different scenes)

steady bobcat
low arrow
#

Ohh, found it

#

ty

gilded jackal
#

Hi i need help with this erroes

#

i have no clue what they mean

rigid island
blissful star
#

anyone here familiarized with fish-net networking?

blissful star
#

thx

night comet
#

Could someone help me with this code, i wanted to add a knockback effect when the enemy hits the player but it didnt seem to work. i tried to simulate it and found out that the moveInput was resetting the x velocity.. there must be a simple way to solve this right

private void Update()
{
if (Input.GetKeyDown(KeyCode.K))
{
    rb.AddForce(new Vector2(-100, 100), ForceMode2D.Impulse);

}
Attack();

movInput = Input.GetAxis("Horizontal");

Jump();


        rb.velocity = new Vector2(movInput * moveSpeed, rb.velocity.y);
        
    
    clampedX = Mathf.Clamp(rb.velocity.x, -maxAllowedVelocity, maxAllowedVelocity);
    clampedY = Mathf.Clamp(rb.velocity.y, -maxFallSpeed, maxRiseSpeed);

    rb.velocity = new Vector2(clampedX, clampedY);
}
}
somber tapir
leaden ice
tawny elkBOT
tough obsidian
#

Hi everyone,
I have an issue regarding the TMP plugin :
I am making a WebGL game and the issue I'm facing is the TMP text appears to be fine when I am playing inside unity play editor but as soon as I upload it on a site (itch.io) the text shows up initially but when I switch to full screen the text seems to be disappearing from the game and when I load the game on full screen the text appears but when I exit the full screen mode the text vanishes
Is there something I'm missing here or is this an issue with the tpm or is this the issue from the website side? For now I have used legacy text which is working fine but because of legacy I can't use the option given in tpm and I can't design the text on my own from unity

wind sequoia
#

so i made a helper function in another script to return a random bool by weight but it keeps returning false,if i do it without the weight parameter it works with no problems,does unity have problems with handling methods with parameters? (i also tried the unity random instead of the system one but it also gives the same result)
public static bool RandBool(int Weight) { System.Random r = new System.Random(); int result = r.Next(0,Weight); if(result == Weight) { return true; } else return false; }

dusk apex
wind sequoia
#

yeah i used that just for testing but i tried with the unity random generator and it still wont work

chilly surge
dusk apex
#

Log what the value of weight is.

wind sequoia
chilly surge
#

If you can properly answer this question, the reason why your code doesn't work should be very obvious.

dusk apex
#

Place some logs and see why the result isn't the same as the acquired value - reminder that you should not be creating a new generator

chilly surge
wind sequoia
chilly surge
#

You haven't answered the question.

dusk apex
#

Meaning the value can never be the same as weight

wind sequoia
#

yeah that too but the unity one is inclusive and that one doesent work either

dusk apex
#

Only float would be inclusive as the Random Range pattern often is used for selecting indices within some count/length of a collection - not ever wanting the count/length

wind sequoia
#

it is? wait let me check

chilly surge
#

That's why I asked that question, if they have actually read the docs and tried to answer it, they will realize it can never return true.

wind sequoia
#

it is...i thought it was inclusive too man working and programming messed me up damn

steady bobcat
#

int to int random ranges are usually inclusive exclusive so its easy to use with arrays/indexed collections

placid edge
#

is it a problem to make a script only for it to have 1 or 2 lines of code or should I merge lots of little scripts like this and differentiate what on the script they can do based on like their name/tag/layer/etc?

night harness
#

Depends on what they are doing

#

You shouldn’t be differentiating like that using names/tags/layers though

#

Maybe tags to filter the start of certain things but

placid edge
#

sure, i'd probably use like a var of sorts to classify the object or something

#

i guess my issue here is that i have a button i want to make, and it only does one thing, and i dunno i feel like i could put this inside another script and have it be called if button exists or something similar, you know?

steady bobcat
#

its better to make things to work with specific types as name/tag comparisons will be slower if used a lot

placid edge
#

it wouldnt be any old script, there's a handful of scripts here that are all related

night harness
#

Depends on what the button is doing

placid edge
#

its just destroying game objects and updating int values

night harness
#

buttons shouldn't be in charge of that imo, depends on how far we're caring though

placid edge
#

its searching for specific children in a gameobject and destroying them if you need more info

#

well its supposed to be a reset button, so i dont know how else id do it ;/

#

one way or the other they gameobjects have to go away

steady bobcat
#

Button -> UI script -> object -> RemoveChildren()

night harness
#

ideally almost nothing should be searching for specific things like that in almost any context btw

I mean more-so logically. if you imagine a big button wired up to some classic western TNT, it's the TNT that explodes, not the button

in this case I mention it because while the button might only have one job, here it should probably be telling something else to do something

placid edge
#

so it should tell the parent object to blow up the kids?

night harness
#

depends on how naughty they are being 😛

placid edge
#

🤔

night harness
#

code wise it's a good habit to try and avoid acknowleding the parent/child relationship of objects unless it's directly related (eg. how transforms are different depending on their parents/children)

#

you should be referencing objects and/or classes explicitly via exposed references in your script

placid edge
#

is it still slow if i find by name inside a gameobject?

night harness
#

slow and bad

placid edge
#

😭

#

should i just make it public and drag the item in there then?

night harness
#

yup

placid edge
#

i dont know why but i remember having too many publics being bad

night harness
#

ideally public should be used only when neccasary but its more for better code practice than actual game-changing. in this case you could avoid it by doing [SerializeField] before your field which lets you keep it as private/protected etc. but still exposes it in the inspector

placid edge
#

Mmm i almost got it, im having an issue trying to check if a gameobjects children have children too

#
        {
            if(gridblock.transform.childCount > 0)
            {
                Destroy(gridblock.transform.GetComponentInChildren<GameObject>());
            }
        }```
dusk apex
#

Looks like a bad idea unless you've got very few objects in the scene

cosmic rain
placid edge
#

ah, i see what i can do

#

no nevermind lol

last quarry
#

Although I prefer transform.children for clarity.

placid edge
#

alright i got it to work, but does this look good or can i simplify it?

#
        {
            if (obj.transform.childCount > 0)
            {
                Destroy(obj.transform.GetComponentInChildren<DragThisItem>().transform.gameObject);
            }
        }```
#

grids is a list of 9 gameobjects im setting on awake

last quarry
#

Can't you make a list of DragThisItem instead?

#

GetComponentInChildren can return null.

placid edge
#

no you see im checking the list of game objects to see if they have children, and the children will always have DragthisItem

placid edge
last quarry
#

That's an assumption.

placid edge
#

wdym?

lean sail
last quarry
#

If the objects have a child without DragThisItem, it will fail.

placid edge
last quarry
#

Yeah but will this be the same two weeks from now?

#

When you don't remember coding this quirk

placid edge
last quarry
#

Yes, that would be cleaner. This current approach feels icky to me.

lean sail
placid edge
#

i mean i dont feel like this will change, its a rudimentary crafting menu with only 4 different types of objects to craft with, but i guess if i felt like expanding later. plus im always bad at optimizing, is half the reason i come here 😭

last quarry
#

I'm more concerned with code quality than optimization here. GetComponent isn't slow enough to care about most of the time.

placid edge
#

Getchild(0) should be fine if the object can only ever have one child right? i cant seem to find some sort of destroy all children without running a loop which i feel is pointless cuz you know, 1 child...

night harness
#

its not pointless

#

it's safe

last quarry
#

It's defensive coding. You're protecting against future changes, and my instincts say that they're likely.

placid edge
#

well its a crafting table, like minecraft, youre not really supposed to have more than one item in the slot

night harness
#

the code shouldn't break if that assumption breaks like that

last quarry
#

Yes but they may have other children in the future if you ever add functionality

placid edge
#

i guess what im trying to say is would a loop slow it down more than just something like GetChild?

night harness
#

not in any way that would ever remotely matter

placid edge
#

oh ok

last quarry
#

Seeing this doesn't trigger any performance alarm bells for me

#

This is something that gets executed once at a time, right? You can get away with a lot of looping in such a context.

lean sail
placid edge
#

yep, all seems to work now. thanks guys 😊

placid edge
last quarry
#

What instantiates them?

#

It seems to me that class should also be responsible for destroying them, and generally keeping track of them.

placid edge
#

a parent gameobject instantiates them when it no longer has a child (the child is dragged and dropped unto one of the grids, which parents it to that grid)

lean sail
placid edge
#

that is what im doing

#

the parent spawns one when it no longer has a child, as i dragged the child somewhere else and parented it to it.
Then im destroying all these children that ive parented to the grid as a reset button

last quarry
#

If the parent is responsible for creating it, it should keep track of it and destroy it.

placid edge
#

but im deparenting it, and the new parent is dealing with destroying it, that's what we were all talking about before no?

patent reef
#

Has anyone completed the create with code thing

vestal arch
tawny elkBOT
lean sail
placid edge
#

oh yeah it's doing that nw

shadow wagon
# vestal arch not sure what that is, but if you have a question, don't ask to !ask
Unity Learn

In this official course from Unity, you will learn to Create with Code as you program your own exciting projects from scratch in C#. As you iterate with prototypes, tackle programming challenges, complete quizzes, and develop your own personal project, you will transform from an absolute beginner to a capable Unity developer. By the end of the c...

#

Looks fairly straightforward

solid iron
#

Im curious

#

What was everyone's first project?

dry mica
solid iron
solid iron
#

When did you start this project?

dry mica
#

A few months ago

solid iron
#

No AI?

dry mica
#

Completely dived in no experience

dry mica
#

I can code well now aswell

#

And model

solid iron
#

Degree?

dry mica
solid iron
#

College Degree

dry mica
#

No

#

I ain’t in college

solid iron
#

What type of brain does one have to possess?

#

Well, I've never stepped into VR so...

dry mica
sleek bough
violet nymph
#

VR for me is actually easier than pc, but it's personal experience that changes that

solid iron
dry mica
solid iron
violet nymph
sleek bough
solid iron
#

It is for help Fogsight

dry mica
solid iron
#

I'm a beginner of course I would want to know ppl's first projects

sleek bough
#

@dry mica Don't ping people not in conversation with you. If have a question then !ask it.

tawny elkBOT
dry mica
#

!ask what do I do when the android build support doesn’t download

tawny elkBOT
dry mica
#

No work

fierce radish
#

I have an issue in my game right now to where i have a script that allows the enemy to wander and follow the player if close which works but my issue is my enemy character falls flat on its face once the game starts and just drags on the ground. I don’t know if its something with the navmesh or what but Ive been struggling for a minute. If someone can help me please let me know

sleek bough
solid iron
#

unless it's a 3D game

sleek bough
violet nymph
fierce radish
solid iron
violet nymph
#

Under constraints

sleek bough
fierce radish
#

Trying it now

sleek bough
solid iron
fierce radish
#

Wouldn’t call it spamming. He/she did give me a similar answer 😂

vestal arch
fierce radish
#

I think i figured it out. Its due to the avatar configuration. Basically when i imported it the avatar started with its x axis rotated 90 degrees and i was setting it back to zero. Especially 0 is it flat on its face and 90 was it standing up

#

So even when freezing x and y it would still go to zero😂

sly shoal
#

i have an object with a bounding box and have a function that checks if the bottom of the object is touching the ground via a boxcast

    public bool IsGrounded()
    {
        //Build an rectangle cast based on the width of the object's bounding box and extends 0.1 units below it. Returns true if touching terrain collision layer.
        return Physics2D.BoxCast(new Vector2(coll.bounds.center.x, coll.bounds.center.y - coll.bounds.extents.y), new Vector2(coll.bounds.size.x, coll.bounds.size.y-(1.5f*coll.bounds.extents.y)), coll.gameObject.transform.eulerAngles.z, Vector2.down, .1f, colliderBlocks);
    }

The boxcast is represented by the thinner rectangle under the object. The issue is that when the object is turned, the boxcast remains at the 'true' bottom of the object, instead of rotating along with the transform. This means that if the object is rotated, the ground check is on the wrong side of the object, and if the object's scale isn't a 1:1 ratio, the size of the boxcast changes too.

is there some way to keep the proportions the same and position/rotate the boxcast to always be relatively below the object?

sleek bough
#

It looks like it maybe affected by the scaling dimensions. If you scale something you should make sure that it is a child object and not parenting something under it or using its dimensions for calculation (or include scaling into it).

#

Anchor point used for calculation on the unscaled parent object and use that as casting coordinate

leaden ice
sly shoal
#

oh you mean including the z rotation in the boxcast check

#

should it just be 0 degrees then?

leaden ice
#

yes

sly shoal
#

yeah you're right, it was redundant

sly shoal
sleek bough
#

Right, bounding box report correct dimentions on scaling.

sly shoal
#

i dont quite understand

#

when the transform rotates, and therefore the bounding box rotates, i want the boxcast check to rotate too. since the left and right sides of the box collider are shorter than the top and bottom, when the object is rotated, the boxcast shrinks to match the length of the new bottom of the object (what was previously the left side)

sleek bough
#

You'll need to detect which way bottom is facing.

sly shoal
#

i basically want the boxcast to do this

sleek bough
#

Bounds return box that doesn't care about rotation

sly shoal
#

i know transform has transform.bottom and stuff which also changes when the object rotates (i think)

#

so transform.bottom should always return the correct side of the object

sly shoal
#

how would i change the code to stick to whatever the transform.bottom is?

#

i guess i could save the bounds to their own variables at startup and use those instead

sleek bough
#

There's no transform bottom, you can infer current rotation from .z rotation value

#

90 = right, 180 = up, etc.

sly shoal
#

which is just the relative bottom of any object

leaden ice
#

yeah that'd be -transform.up

sly shoal
#

yee

leaden ice
#

you can use that as your direction vector instead of Vector2.down

sly shoal
#

Vector2.down in boxcast is the direction the boxcast moves to look for collisions

sleek bough
#

Note if rotation is slightly off, comparing to vector directions might fail.

sly shoal
leaden ice
#

you want it go to down relative to the direction the object is rotated

#

which would be -transform.up

sly shoal
#

ohh you're so right

#

thank you

wraith spear
#

Is there a way to reference Components in the Editor? I'm guessing there is, since it's possible with Buttons (see screenshot), but I'm having no luck with discovering how.
I want to be able to reference any Component through a SerializedField and then disable it in script

leaden ice
#

you could use Component but Behaviour is the subclass that has .enabled

#

The screenshot you shared is from a UnityEvent which actually allows any UnityEngine.Object, not just Components.

wraith spear
# leaden ice `public Behaviour myReference;`

I tried Components and Behaviours, but as you said Components don't allow disabling. With Behaviours I'm having a hard time selecting the actual Behaviour I want to disable, however. I can only drag in/ select GameObjects and get a seemingly random Behaviour each time

leaden ice
#

this will open a special inspector window for that object

#

you can then directly drag components from the regular inspector window into it

wraith spear
leaden ice
#

Note that Colliders and Renderers have .enabled but they don't derive from Behaviour, so if you want to include those you'd have to do something like:

public Component theComponent;

void DisableIt() {
  if (theComponent is Behaviour b) b.enabled = false;
  else if (theComponent is Renderer r) r.enabled = false;
  else if (theComponent is Collider c) c.enabled = false;
  else Debug.LogWarning($"Cannot disable {theComponent}");
}```
wraith spear
#

Thanks for the information. This'll do finely for now, and later on I think I'll write a custom drawer to make it less finnicky

elder gust
#

Anyone got tips on optimizing my game? I’m using the urp

leaden ice
#

repeat until you are satisfied with performance

vestal arch
leaden ice
vestal arch
#

i mean why colliders/renderers define their own enabled rather than deriving from Behaviour

leaden ice
vestal arch
#

there's no satisfying answer here, huh 🥲

#

i'd have guessed it was because enabled affects more than Update being called for those components

leaden ice
#

Those components are implemented natively

#

they don't really use Update, not the way user scripts do

last quarry
zinc parrot
#

Whats the proper way to profile specifically SetData calls? or would it be better to convert my SetData to cmd.SetBufferData and profile that?

whole sorrel
#

So, when trying to build my game I get this type of issue about type or namespace not existing

However in the editor everything is working. Most are from libraries, like this dev.nicklaj.butter is one of my libraries, while GgCore is a dependency for Folder System

Everything works in-editor but I can't get to deploy so could anyone explain what I'm doing wrong?

Use the Folder System - Gaskellgames from Gaskellgames on your next project. Find this utility tool & more on the Unity Asset Store.

leaden ice
whole sorrel
#

I have A LOT of issues with dev.nicklaj.butter so I suppose I setup something in the wrong way in the assembly but I wouldn't know what. It's basically my own implementation of SOAP and everything is distributed as editor stuff https://github.com/xNicklaj/Butter

leaden ice
#

Is your asmdef set up properly?

whole sorrel
whole sorrel
leaden ice
#

The asmdef likely should be set to compile only in the editor

whole sorrel
#

I haven't really understood what's supposed to go in editor and what's supposed to go in player in the package thingy

#

I have everything in editor

leaden ice
#

For example my Editor assembly is set up like this

#

it only will compile in the editor

whole sorrel
#

Huh I see

#

When should something be compiled for editor only?

leaden ice
#

when it's only for the editor and not for the build

#

e.g. it's editor tooling

whole sorrel
#

Like in my case I suppose drawers are supposed to be editor only, while the rest is supposed to be for the build? Because it's things like scriptable variables, etc etc

leaden ice
#

you need to split them up

whole sorrel
#

damn

leaden ice
#

You should have two assemblies. One for editor, one for runtime

#

the editor one can reference the runtime one, but not the other way around

whole sorrel
#

but like scripts that go into game objects are supposed to go to runtime, right?

#

and also scriptable stuff

leaden ice
whole sorrel
#

Thanks, I'll try to fix this

#

you helped a lot

#

So now I setup everything in the following way

Green is in package/editor, red is in package/runtime

Each has its own asmdef of course, one is .editor and one is .runtime

What is happening now is that since I've separated the editor tools from the runtime stuff they can't see each other. How can I fix this? (first time making a package)

#

Notice also how both can't see each other, not only editor -> runtime

somber nacelle
#

the stuff in your runtime assembly should not be accessing things in your editor assembly, your editor assembly can reference and use things in the runtime assembly though provided the asmdef has a reference to that assembly. but that dependency should only be one way because the editor stuff simply won't exist in a build so you won't be able to build at all if your runtime stuff uses editor stuff

whole sorrel
#

I think I understand

#

So if I provide a way for others to create their custom drawers, I should also mention in the docs that their code should also be enclosed in a separate editor-only asmdef?

somber nacelle
#

yes, or in a folder called Editor

whole sorrel
#

Is there anything special about folders called Editor?

somber nacelle
leaden ice
whole sorrel
#

Ah thanks!

#

Yeah my package is safe now

#

time to figure out all the other issues lol

steady bobcat
whole sorrel
#

Okay

#

This would have saved me some time to know ealier

#

thanks

steady bobcat
whole sorrel
#

Thank you!

#

In the build, should I specify anything about my package name?

#

What I mean is, my editor can find my namespace

Dev.Nicklaj.Butter

and all its related functions. The scripts inside the package work, BUT when I try to build I get this:

So it's like my project scripts cannot access the namespace when building?

#

These issues are not there in editor ofc

#

I have it setup this way though

#

The only thing I could think of is that in my runtime asmdef I have turned off Editor, not sure if that's wrong?

steady bobcat
#

well yea its gonna need to be used in editor if you want to actually do anything 🤔

whole sorrel
steady bobcat
#

is this code editor or debug only?

whole sorrel
#

No it's runtime stuff

#

Pff I'm a moron

#

it's exclude platforms

#

not include platforms

steady bobcat
#

HA

whole sorrel
#

Why is it though?

#

the editor asmdef has include platforms not exclude

#

the runtime has exclude

#

I'm being played man

steady bobcat
#

there is a checkbox to invert it

whole sorrel
#

Oh makes sense

#

I should sleep more than 3h a night I guess

steady bobcat
#

hopefully thats a joke cus little sleep over long periods is really dangerous

karmic stone
#

Quick question, how do you get the value out of a Tvalue, assuming you know exactly what type of value the result will be? Unity internal uses Tvalue, and im overriding a callback function to check the value of that callback, if it is 0 or 1, return, otherwise let it continue to work. (I know that i will only use it for 1 type of value, but unity itself doesnt know that)

protected override BindingResult UpdateUI<TValue>(in BindingContext context, ref TValue value) {
    
    if((int)value <= 1) {

    }
    return base.UpdateUI(context, ref value);
}
steady bobcat
#

its a generic type so cast it or use it as the declared base type

chilly surge
#

You can use pattern matching if (value is int i && i <= 1).

whole sorrel
karmic stone
#

ive used the is keyword for bool checking, but didnt know you could get it out

steady bobcat
#

if you know its only to use with an int then why do funky business casting it

karmic stone
#

Its an override of a Unity function, so i didnt know if casting it would give a wrong signature

steady bobcat
#

generic args are not some special unity thing and your overload should be valid

#

to be clear, overload and not a override if done differently

karmic stone
#

ahh, im doing an override, as im trying to stop some unity functionality in a callback, rather then creating a seperate method. turns out it doesnt work right with override, so funky type casting it is for now.

steady bobcat
#

do remember to write back to value if you want to modify it as the cast will unbox it (i presume TValue is object)

karmic stone
#

Thank you, will keep in mind if i need to write back to it. How I'm doing it now is that if it satifies the condition, i do stuff with the context and return a sucess, rather then calling the base.

whole sorrel
#

Does anyone know why building cannot find the unity default screen space ambient occlusion?

lucid brook
#

Is it possible to get the normal of a collider from a OnTriggerStay like you can with a raycast?

somber nacelle
#

the parameter for OnTriggerStay is just the collider so you would need to separately query it for the normal with some sort of cast, although what would you expect the normal to be when one object entirely overlaps the other?

cosmic rain
warm badger
#

in my openworld game, I have divided the whole island in 64 chunk scenes so that only those chunk scenes are loaded which are near to the main character .

What I wanna do is batching the objects of those specific chunks loaded around the player in runtime
But the chunks will also unloaded when the player isnt near to those, but runtime static batching already makes up a huge combined mesh (which was created when the player was around those chunks of that island) , but now the combined mesh are still on the memory , thus when the player moves around different region of that island , the memory gets overloaded with those combined meshes created every time

I need to make those combined mesh's garbage created by runtime static batching instantly removed from the memory when the player is not around the chunk of those objects (combined mesh)

What should I do in that case? Please help dont ignore....(

cosmic rain
warm badger
cosmic rain
#

If it doesn't, then your only option is to write your own batching implementation

warm badger
warm badger
#

Im stuck here , it seems Im close to the solution but no clue how to head towards further

cosmic rain
# warm badger but in my case , the combined mesh created by runtime static batching , I dont k...

Since you don't have any reference or handle of the mesh, you can't really destroy or release it manually.
And since the documentation doesn't mention anything about it's lifetime, you can only act based on assumptions.
Or you can change your implementation such that it doesn't rely on API that is so obscure.

If you chose to rely on assumptions, you could assume that it is collected by GC according to the same rules as any other asset. You also need to assume that it's only ever referenced by objects that you can destroy and not by some internal unity systems.
If these 2 assumptions are true you need:

  • make sure that it's not references by objects in the scene. Another assumption is that it's referenced by the mesh filters that were used when combining it. If so then you'll need to make sure that they don't reference it and/or are destroyed.
  • As most assets, it wouldn't unload automatically when there are no scene references. You need to either transition scenes, or call API to trigger collecting of unused assets. I think it was Resources.UnloadUnusedAssets();.
whole sorrel
#

I have a question about scriptables.

If I have this scriptable object, that PersistencyId is a string variable that is modified like this:

private void OnValidate()
{
    if(string.IsNullOrEmpty(PersistencyId))
        PersistencyId = Guid.NewGuid().ToString();
}

So my assumption is that whenever a new scriptable object of this type is created the UUID is assigned and then never touched again. When building, the resulting scriptable will have the PersistencyId that was assigned by the editor OnValidate. Is this assumption correct?

#

My head tells me it is, however my player gives me a null Persistency Id

#

So basically I want this value to never change across launch, because I will use it to find the correct identifier when saving and loading data

quartz folio
#

This setup won't de-duplicate if you copy an SO.
I also really hate OnValidate and don't recommend using it for almost anything.
Check that you're actually serialising the field, because it appearing greyed out in debug view would indicate to me that it's not

whole sorrel
#

Why do I need the field to be serialized? I don't need to change it via the editor

night harness
#

fields being exposed in the editor are a byproduct of serializg them

#

thats not what serializefield actually does

#

serializefield ensures the value is actually saved (serialized) to the asset file

whole sorrel
#

oof shit

#

that's probably what's going on

#

What does it mean when SerializeField is grey?

vestal arch
#

it's unnecessary/redundant

whole sorrel
#

Attribute 'UnityEngine.SerializeField' is redundant on this declaration type. It is only used when applied to 'Field' declarations.

Ah so the thing is that I have this IPersistentData that defines PersistencyId and it's not accepting the serializefield due to that I believe

vestal arch
#

public fields are already serialized

whole sorrel
vestal arch
#

oh wait that's a property, mb

#

serializefield doesn't work on properties the same way, you need a different form

vestal arch
whole sorrel
#

Can I inherit a field from an interface?

vestal arch
#

interfaces can't specify fields

chilly surge
#

You can use [field: SerializeField] on the property to have it serialize the backing field.

#

Or write the field normally, and do an old school implementation of the property.

quartz folio
#

It probably shouldn't have a public setter too

whole sorrel
#

Huh with

[field: SerializeField, HideInInspector] public string PersistencyId { get; set; }

it disappeared entirely from the inspector in debug mode. Does HideInInspector also hide it in debug mode? I thought debug mode would show everything

quartz folio
#

Annoyingly it does affect debug mode

whole sorrel
#

Anyways it works now, thanks everybody, I learned a lot

Using [field: SerializeField] is very useful.

mighty gulch
#

Hi all 👋🏻

I'm writting to seek help in troubleshooting why "isOpen" bool variable value gets overridden from the initial "False" at Awake method to "True" when the OpenSideBar Method is called.

I've attached the script to the MainSidebarMenu prefab with StartOpen value set to False. MainSidebarMenu prefab is active in the scene. A button: "MenuButton" has OnClick event with MainSidebarMenu linked and OpenSideBar method chosen.

I've already reset the button and attached the method 4 times and I very confused why my isOpen value is True when I first click on the MenuButton. Second image depicts the logs, which clearly show that isOpen value is set to False on Awake and then due to some reason becomes True when I click on Button with OpenSideBar method attached.

Thanks everyone who can help in advance!

steady bobcat
#

Make sure your VS is set up correctly too as it appears to not be (is the project generated solution open?)

mighty gulch
steady bobcat
#

Lack of colour on these made me think its not.
Does the bar below the file tab say "Miscellaneous files" ?

#

anyway its a common issue for new people here: !ide

tawny elkBOT
mighty gulch
#

@steady bobcat I've fixed the issue. I've used Perplexity to find similar issues and it turned out to be quite a common problem in Unity. I added: "static" keyword to the private bool variable and now nothing changes!

Thanks for help

steady bobcat
mighty gulch
steady bobcat
delicate granite
#

hi, i wanna make a player and enemy scripts which will have stuff like health, attack, and all that.

i have a basic outline but i'm not sure how to make it work.
the line csharp public class Enemy : MonoBehaviour at the top there, it takes from monobehaviour. i am unable to also make it take from AIBehaviour. unity then gives me some warning when I don't use monobehaviour. (image below)

will this affect anything or is that just because I've used private/protected variables in AIBehaviour?

edit: By the first line, I meant so I can override virtual voids if need be. I.E. The attack wont be the same of every enemy, but will still use some stuff from the base function

#

hope it all makes sense

vestal arch
#

in this case it's most likely your own mistake of redefining the field that should be inherited

delicate granite
#

should i remove it from aibehaviour then?

#

as it's just there to be set

vestal arch
#

should AIBehaviour have an enemyObj in general?

delicate granite
#

for the attack thingy

delicate granite
vestal arch
#

then yes, you would remove it from AIBehaviour and define it only where it's actually used

delicate granite
#

alright, thanks!

vestal arch
#

(in the alternate route; if every AIBehaviour should have an enemyObj, you would remove the definition from Enemy instead, and let Enemy inherit that member from AIBehaviour.)

delicate granite
#

ahh. every aibehaviour will have attack but not enemyobj. thank you!

woeful hamlet
#

What's the best/most 'clean' way to manage collectible objects that each have a score value? I'm making a 'catch falling objects' game, with food that's worth points and hazards that cost points.
Would it be considered better practice to have their score value in each object/prefab and pass it along to the score manager in an event, or should the score manager have like the master list of scores and decide based on the object (via a 'type' enum).

vestal arch
#

have each object specify its own score

#

think about what you'd do to make a new one

#

in this approach, you'd just make the prefab, set the component, set the score
if you used a centralized store, you'd make the prefab, set a component to make it collectible, then go to the store and set a score there, maybe updating an enum definition and recompiling

last quarry
woeful hamlet
#

And basically the same question about sounds too. Should everything carry its own sound(s) and talk to the Audio manager directly or should all sounds be invoked more centrally?
So I suppose this is actually a very general question I couldn't really find a good answer (esp since most tutorial videos neglect to mention software architecture in general). To what extent should the moving pieces (enemies, colletibles, etc) route their updates and such through some manager, or should they more directly talk to the relevant places? (Audio, score, maybe other enemies)

vestal arch
#

hm this is kinda more about where you keep data
well, the previous question would be about where you keep data
this is perhaps about where you keep links to assets

last quarry
#

Separating data from functionality is generally pretty clean. Keep configuration stuff in ScriptableObject, reference that in your prefabs.

delicate granite
#

sparks up a question, if i'm using inheritance and stuff, do i use scriptable object for the class that will inherit from the big class or do i use that for the big class?

last quarry
#

In C# you can only inherit from one class, so your base class should inherit ScriptableObject

delicate granite
#

ahh thank you

last quarry
#

You can inherit from multiple interfaces. Depending on how much code you share between implementations that might be a better idea.

#

And sharing code can also happen through a third class which is not inherited

delicate granite
#

small brain fart. inheritance is Class1 : Class2 right?

last quarry
#

Yes

delicate granite
#

yeah thanks

#

so if i made a monobehaviour script and just took away the monobehaviour part, all will be fine?

#

i wanna make my code not awful to read

vestal arch
#

then it wouldn't be a monobehaviour...?

delicate granite
#

yeah

#

my brains on a different planet honestly

#

sorry for wasting time

vestal arch
#

if you're talking about the options in the menu you screenshotted above, for a standalone class, you'd probably start with "Empty C# Script"

delicate granite
#

yeah. thanks

#

sorry, my dumb questions are not helpful

woeful hamlet
steady bobcat
#

you make say 5 instances of the SO and assign each to the respective prefab. The point is to separate this data from the prefab.
Also means its easier to share this data with multiple prefabs (or if swapped, share a prefab between multiple SO's)

woeful hamlet
#

So for my primitive example, the SO would have like the score value, falling speed and collision sounds, and each prefab only contains its SO instead of the actual values?

steady bobcat
#

*references the scriptable object asset

woeful hamlet
#

Yeah, that's what I meant, my bad. Probably just via a SerializeField set in the editor?

night harness
#

ye

#

i could be wrong but i think the nitpick there was its SO vs. the SO