#archived-code-general

1 messages · Page 321 of 1

worldly hull
#

finally get things done

  [System.Diagnostics.Conditional("DEVELOPMENT_BUILD"), System.Diagnostics.Conditional("UNITY_EDITOR")]
  public void LogError(string tag, object message)
  {
    Debug.unityLogger.Log(LogType.Error, message);
  }
-> Log
-> LogWarning
-> LogErrorFormat
-> LogWarningFormat
-> LogFormat
-> LogException```
#

its custom logger

thin aurora
#

I would not rule out error logging in a production build. I would instead hide them in log files

#

Hiding error logging would make it very hard to tackle errors that only happen in production

#

Otherwise consider setting up configuration that allows you to specify a minimum and maximum severity with logging, which can be adjusted to easily test for errors by adjusting the configuration

worldly hull
#

my team lead said he didnt want any debug.log occurs or process during production stage as every debug logs will slow down the app

#

whether its logwarning or logerror

thin aurora
#

Modern loggers do not slow down the app at all

worldly hull
#

you know during development mode you get a small windows that can display errors and exceptions right?

pine condor
#

recently had to scuff my way into getting rid of a warning unity has with instantiation in onvalidate

thin aurora
#

Serilog for example writes its sinks asynchronously

#

So you can use that with no issues

worldly hull
#

previous team members gone lazy, they wanna check certain important messages quickly on that windows, so they delibrately make ~200 log , that is supposed to be a normal log, to become logerror

thin aurora
#

Also, usually error logging doesn't occur, so why optimize logging by removing any instances of that? 🤔

worldly hull
#

so 40% of logerror might not be an error at all lol

somber nacelle
#

your team members need to learn to use the debugger

thin aurora
#

I would say that these log messages are removed instead then

#

That sounds very chaotic and bad

worldly hull
#

last time i checked such debug logerror has 305...

#

this gonna be hard lmao

somber nacelle
#

tracepoints > hundreds of debug.log calls

thin aurora
#

That sounds like something that anybody would have rejected with a simple review

worldly hull
#

i can still see some deprecated or unused code thruout the codebase until today, thats 3-4 yrs old

#

we just keep adding things on top

#

i will clean out a very little part of it if i encountered them

#

ok you know what, i couldnt do much about the code now, we will push out the new production in next few weeks, but for debug logging i gonna fix errors and exceptions so they can go well on production mode as well

#
debug that confirmed to be ruled out of production mode:
-> Log
-> LogFormats and all of its variants
-> LogWarning

debug that will preserved during production mode:
-> LogError
-> LogExceptions```
thin aurora
#

Yeah that seems reasonable

#

I'm not 100% familiar with how much is allowed with consent but you can also send these errors/exceptions to a server if they happen to somebody

#

@worldly hull

worldly hull
#

like our game server? or database?

#

actually we dont store errors and exceptions on client app side tho

#

like we dont have a database or server to do that, if errors happened it will stay in users local storage i think

#

the logs

#

server side errors will have records , its more secure and tidy

thin aurora
#

Makes it easy to handle things that might be thrown on the client and cause crashes

worldly hull
#

yeah that sounds good 👍

#

ty i gonna fix the 300 logerror first lol

quartz anchor
#

Hey everyone!
I'm trying to make a UnityEvent which I then add listeners to from another script (code: https://pastebin.com/MVmETYxq)

The problem is that I can confirm that the event is invoked and that the other script tries to add its listener but it seems like it's never added as it's never called

Thank in advance for any help!

thin aurora
#

Seems weird to not just have it as static, and to write to some instance, but perhaps this is with a reason?

worldly hull
#

i tried once tho

#

to make this "LogOnDebug" as a public static class?

thin aurora
#

General thing you could consider is to create an instance of the logger for each class requiring logging, and to accept a generic type that accepts the class type. Then you can write the class name and namespace to logging to accurately determine where logging was called.

worldly hull
#

but u cant implement interface for it?

thin aurora
#

FYI this is also how .NET does logging, it has dependency injection and allows a ILogger<out class> class for logging

#

I have this for example:

internal sealed class ConcurrentServerDataProvider : IServerDataProvider, IDisposable
{
    /// <inheritdoc cref="ILogger"/>
    private readonly ILogger _logger;

    public ConcurrentServerDataProvider(
        ILogger<ConcurrentServerDataProvider> logger)
    {
        this._logger = logger;
    }
#

Then all logs will be displayed under that specific class

worldly hull
#

looks cool

thin aurora
#

.NET also allows you to set severity per class if you have this

#

So if one class logs way more than what you want you can just turn it off for the whole namespace

#

So maybe this is useful in your case with all the excess logging

quartz anchor
leaden solstice
quartz anchor
lean sail
quartz anchor
leaden solstice
#

(In)sanity check

lean sail
quartz nova
#

Hello friends, I'm struggling, someone help me pepehands

I have a Isometric Y as Z tilemap and want tiles to be highlighted on mouseover using a sprite which is already on the scene but will show and switch positions when hovering over tiles.

  • Cell size of my isometric cell layout is 1, 0.5, 1
  • The projects Transparency Sort Mode is set to Custom Axis with following values: 0, 1, -0.26

What I have tried:

  • Get mouse position by using Input.mousePosition
  • Convert the mouse position to world position using Camera.main.ScreenToWorld()
  • Convert the world position to cell position calling the grids WorldToCell() method
  • Change the position of the highlight sprite to the cell position

But the position is off like half of the tiles width in px.

quartz nova
pastel plover
#

Hey guys so like I’m trying to code a game timer but for whatever reason when I paste the script into the camera on the timer text box I cannot select it

zenith bear
#

On my laptop I got a hardrive and all my downloads I download is going to my C drive but I want it to go to my hardrive does anyone know how to fix it so when I download something it goes to my hardrive instead of C drive

pastel plover
#

It’s just weird

leaden ice
knotty sun
somber nacelle
zenith bear
#

Idk where else to ask

leaden ice
# pastel plover

Drag and drop, and make sure the type of the thing you're trying to drag is correct. Looks like your code wants Text which is the legacy Text component. You sure you don't want TMP_Text?

zenith bear
#

I just assumed people in here would know how to fix it

sleek bough
#

@zenith bear This has nothing to do with Unity. Put it in google

pastel plover
#

I guess I could try that

#

Drag and drop won’t work thought, the box is refusing to accept the asset which is UI text

leaden ice
#

Unless you specifically used the Legacy Text component

pastel plover
somber nacelle
#

look at the component you want to assign to it

leaden ice
pastel plover
#

Alright hold on

subtle path
#

is there a way to access the prefab preview image?

pastel plover
#

Yh it’s text mesh pro

leaden ice
#

Then you have your answer

pastel plover
#

So I got to convert it to legacy?

leaden ice
pastel plover
#

Aha

leaden ice
#

In the way I explained above

subtle path
leaden ice
#

Why not

#

What goes wrong with it

#

That's the way to do it

subtle path
#

it tells me value is null

pastel plover
#

Hmm would I change the null value ?

leaden ice
#

Can't help you without more information

subtle path
#

i was about to give some...

leaden ice
#

Then you can assign it in the inspector

#

But first you have to change the code

#

Also please stop sharing phone photos

subtle path
#
        private void CreatePreviewImage()
        {
            string path = AssetDatabase.GetAssetPath(this);
            string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path +      "/Level Previews " + typeof(Level).ToString() + ".asset");

            Texture2D prefabPreview = AssetPreview.GetAssetPreview(this);

            AssetDatabase.CreateAsset(prefabPreview, assetPathAndName);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }```
i try to get the object but the compiler says its null
leaden ice
#

Compilers don't do such things

#

That's a runtime exception

#

Nothing to do with the compiler

#

Which line is line 50?

#

Of GenerateLevelPreview.cs

#

Seems unrelated to this code you shared

subtle path
#

yes it was. its the wrong error. gimme a sec

pastel plover
#

Perfect it works now tysm!

versed loom
#

whats the best way to get the name of an enum, Enum.GetName or tostring ? i think its getname but it has boxing

leaden ice
#

Like the name of the value?

versed loom
#

yep

leaden ice
#

ToString()

versed loom
#

tyy

quartz nova
#

@leaden ice Friend, I tried it out.

#

Can't confirm that it works, since I don't see the tile highlight.

#

I'm sure this is due to the Z position?

#

Doing += 1 just for testing also didn't change anything.

#

I'm on my PC now, can also show code/screens if needed.

quartz nova
#

But the difference is not worth mentioning

heady iris
#

I use it just to be consistent, since I'm already using Enum.GetValues, etc.

quartz nova
#

@leaden ice Camera.main.nearClipPlane it is!

spring flame
#

does anyone know how to enable intellisense in rider for unity packages? Fro example I want to be able to navigate between symbols in the Packages > ReadOnly > Modules > Shader

#

it's ignored, a part of unity package cache and analysis is OFF (on the right)

thick terrace
#

you should be able to turn that on in preferences > external tools

spring flame
#

in unity or rider somewhere?

swift falcon
#

help

public AudioSource passosAudioSource; // Referência ao AudioSource para os passos
public AudioClip[] passosAudioClip; // Array de clips de áudio para passos

void Passos()
{
if (passosAudioClip.Length > 0 && passosAudioSource != null)
{
passosAudioSource.PlayOneShot(passosAudioClip[Random.Range(0, passosAudioClip.Length)]);
}
else
{
Debug.LogWarning("ReproduzirPassos: AudioSource ou AudioClip não foram atribuídos corretamente.");
}
}

leaden ice
lusty zephyr
lusty zephyr
spring flame
lusty zephyr
swift falcon
#

i wont post

#

i just want to use it as a way of learning

lusty zephyr
hollow hound
#

I have Particle System as a child object. I want particles to continue to exist after parent destruction. I trying to unparent particle system in the OnDestroy, but particle system "resets" when I do this, just starting playing from the start. I believe that's happening because parent object already marked as "ready for destroy" and this affects how particle system behaves.
How can I solve this?

hard viper
#

then don’t parent it

#

make a separate game object that just follows the other object

hollow hound
hard viper
#

just copy over the transform matrix every frame to the particle system object

#

at least i think that is how it works, because particles tend to live in their own little world after being instanced

#

once a particle is made, you can’t touch it

#

you can’t read, access, modify, or delete it individually

hollow hound
# hard viper then don’t parent it

So there is no more optimal way to solve this issue without creating empty objects that follows everything I want particle system on, and managing this object, their destruction and all that?

hard viper
#

you could make the particle system the parent of the object, but you still need to then make all changes to the parent, which is like a backwards hierarchy

#

or a parent objec that has as children the particle system obj, and the actual object. But this is just an organizational difference in the hierarchy, equivalent to what we discussed earlier

#

but point being: if your particle system component is on an object that gets destroyed/disabled, then that shit is gone

hollow hound
#

For the context: it's a burn effect on enemies that instantiated in the runtime and I want it to disappear smoothly

hard viper
#

i understand the use case

#

it changes nothing, as that is normal

#

for reference, in SM64, particle sprites are like separate objects

#

like little dust clouds and shit are like separate entities

#

just so you have some context

#

either way, if you want something to exjst on the board, it needs to exist. and you can’t have something exist when it is also supposed to not exist from being destroyed

hollow hound
hot urchin
#

Can anyone help me figure out why my placing system doesnt work

spring creek
tawny elkBOT
hot urchin
#
public bool CheckTile(TileClass tile, int x, int y, bool isNaturallyPlaced)
{
    if (x >= 0 && x <= worldSize && y >= 0 && y <= worldSize)
    {
        if (tile.inBackground)
        {
            if (GetTileFromWorld(x + 1, y) || GetTileFromWorld(x - 1, y) || GetTileFromWorld(x, y + 1) || GetTileFromWorld(x, y - 1))
            {
                if (!GetTileFromWorld(x, y))
                {
                    RemoveLightSource(x, y);
                    PlaceTile(tile, x, y, isNaturallyPlaced);
                    return true;
                }
                else
                {
                    if (!GetTileFromWorld(x, y).inBackground)
                    {
                        RemoveLightSource(x, y);
                        PlaceTile(tile, x, y, isNaturallyPlaced);
                        return true;
                    }
                }
            }
        }
        else
        {
            if (GetTileFromWorld(x + 1, y) || GetTileFromWorld(x - 1, y) || GetTileFromWorld(x, y + 1) || GetTileFromWorld(x, y - 1))
            {
                if (!GetTileFromWorld(x, y))
                {
                    RemoveLightSource(x, y);
                    PlaceTile(tile, x, y, isNaturallyPlaced);
                    return true;
                }
                else
                {
                    if (GetTileFromWorld(x, y).inBackground)
                    {
                        RemoveLightSource(x, y);
                        PlaceTile(tile, x, y, isNaturallyPlaced);
                        return true;
                    }
                }
            }
        }
    }

    return false;
}

its says i get the nullreference at the if statement for tile.inbackground

hollow hound
spring creek
hollow hound
# hollow hound I can unparent particle system before destruction of the parent, seems perfectly...

Also, I find some workaround. It works as expected when using OnDisable instead of OnDestroy. OnDisable is also called before destruction (and I think before marking object for destroy), so particle system doesn't resets before unparenting. Kinda works right now, but I don't want to face problems when I will need to use exactly "disable" in the future.

Anyway, seems like there should be a better solution that to create a bunch of empty GOs that follows every enemy just to smoothly stop the emission of particles.
Maybe I can somehow disable this behaviour of reseting animation during destruction process or something like that?

hard viper
#

the other way would be to disable all the other entity components, and all children. instead of destroying it. then wait for some amount of time for particle system to be ready to destroy it

#

but then you made your game logic dependent on your graphics, which is a big nono

#

just make your particle system on a different object. you know the answer that works, and you just trying to tie a component to an object where you need the component to work even after the object is destroyed.

undone prism
#

hey i am in need of some help. i am using wheel colliders to make a realistic car controller. i have made some scripts including a script for anti roll bar and downforce. i used AddForceAtPosition for this but it didnt really work. i was wondering why and tried everything and still no results. my plan was to do it a little bit later into the project and go to the tyre scripts first. when i was looking for some info i saw this guy talking about downforce https://forum.unity.com/threads/the-dark-art-of-unity-wheel-colliders-what-unity-doesnt-tell-you.1109261/ on the forums and wanted to implement this as well. thats when i remembered that i used AddForceAtPosition and have my scripts made in a way that is able to be used with multiple positions on the car. so for each wheel to have the correct downforce or ARB force applied i need to check how much force there is on the wheel. this is where i have no clue what to do and maby need some help for some ideas on how to solve this while not changing my scripts or only the AddForceAtPosition to a different function or something. https://gdl.space/homedajola.cs this are the 2 scripts i am talking about. any help would be fantastic.

primal wind
#

I'm gonna try to setup destructible terrain using the Marching Squares algorithm and was wondering if the points property in PolygonCollider2D needs the array to be in order because i have no idea how to order those so they go from start to finish

zenith bear
#

Hey when I’m trying to download the lts 2022 2 errors comes up, the errors are android SDK & NDK Tools and OpenJDK how do I fix this?

knotty sun
hard viper
hollow hound
# hard viper just make your particle system on a different object. you know the answer that w...

But to particle system object is a separate game object. It's just happens to be a child of an enemy some amount of time. Really don't see any like architectural or logical problem, am I missing something? The only problem is in the this kind of optimisation(or what it is) for ready-for-destroy objects.
Separate empty gameobject that just follows another object seems just like a self-made parenting to me, but I can be wrong

hard viper
#

yes. in unity, child objects are destroyed/disabled if the parent is

heady iris
hard viper
#

that is the fundamental core thing that you seem to not understand

hollow hound
hard viper
#

just start by not parenting them

hollow hound
hard viper
#

if you do not want their fates to be linked, don’t link them like that in the first place

zenith bear
latent latch
#

transform.parent = null

#

don't actually need to detach with particle system. Just Stop() the main particle and coroutine a lingering time before cleaning up

#

the secondary emissions will continue but no more will produce

hollow hound
hollow hound
latent latch
#

I used to do the detach method, but once you start pooling systems it just becomes an annoyance because you want the object intact when returning.

hollow hound
#

Pooling systems?

latent latch
#

Object pooling, like bullets and explosions

hollow hound
#

Hm.. So what would be the problem with bullets/explosion? I can detach particle system of a bullet before bullet destroy and its trail or something else would be there, right? Or what you mean by "returning"?

latent latch
#

The idea of pooling is you don't destroy. You cache a set amount of objects and reuse them.

#

So ideally when you reuse them, they should be in a state such that if you were to instantiate them instead.

#

(VFX Graph is better though but cant use it with webgl)

undone prism
hard viper
#

dynamic rigidbodies are affected by forces

#

and if you find this to be new information, then you are definitely not ready to implement all the forces you would need to make a car drive smoothly as a dynamic rigidbody

unique delta
#

can t use "Using Cinemachine" at the top of the script someone have an idea?

unique delta
#

i get this error : "The type or namespace name 'Cinemachine' could not be found"\

rigid island
#
  1. is the package installed?
  2. are you using assembly definitions
  3. is error in code editor or Unity as well
unique delta
#

the error dosen t show in the script itself just in the unity console. So is something with the unity version?

waxen blade
#

If I have a property that equals an instantiated scriptable object. Later on I instantiate a new scriptable object and set it to that same property. What happens to the original scriptable object that no longer has a reference?

  1. Does it just float around until garbage collection occurs?
  2. Is it recommended that I destroy that instance of the scriptable object after I no longer use it?
rigid island
#

normall its the other way around

unique delta
#

i mean the text isn t hilighted with red

unique delta
rigid island
#

which ide are you using?

unique delta
#

visual studio code

rigid island
rigid island
# unique delta visual studio code

so does it normally highlight red other issues?
anwyay if its also showing error in unity you seem to be missing the package or you have assembly definitions somewhere

unique delta
#

yes it dose and it autocomplete things

rigid island
unique delta
#

so the folder ?

rigid island
#

the folder?

#

do you know what Package Manager is

unique delta
rigid island
#

oh fuck

#

nvm

#

they changed the namespace ffs

#

using Unity.Cinemachine;

waxen blade
unique delta
rigid island
#

still didn't use it so it threw me off 😛

#

after I saw you had 3.1 though it sparked a thought to double check

waxen blade
#

So the instantiated version just goes back into the assets folder along with the original scritpable object?

rigid island
#

is it not in the assets folder? its been a while since I did runtime SOs

swift falcon
#

so like I kinda can't figure out how to make a player movement and mouse movement script

kindred otter
rigid island
#

oh so they are just in memory ?

#

oh right I remember you have to do

AssetDatabase.CreateAsset(theData, path);
AssetDatabase.SaveAssets();```
waxen blade
undone prism
# hard viper dynamic rigidbodies are affected by forces

i searched for this and i can only find dynamic rb's for the 2d rb. i am using a normal rigidbody and i cant find anything on a dynamic setting there. i dont know much about the 2d rb but since the wheel colliders ignore almost all forces i dont know if this would even work. i can be wrong but it sounds really odd to me that the wheel colliders would react differently to another rigidbody. i also tested with increasing the values in the meantime but it only gets more buggy if i do so

hard viper
#

rigidbodies for 3D have different modes, for both kinematic and dynamic

#

i can very confidently recomend you not touch this problem until you learn more

kindred otter
rigid island
#

yeah forgot it was an exclusive method to save, and CreateInstance didn't actually save it

#

i have barely used runtime SO creation

undone prism
kindred otter
# rigid island i have barely used runtime SO creation

Me neither, everytime i start thinking about it, it feels like it would be more appropriate to use a poco or simply some stats on the mb. But i'm not very experienced at designing systems, maybe i'm completly wrong 🙂

rigid island
#

yeah I mean classic itdepends

#

One thing I don't use them for is for mutable data

#

prefer poco for that

hard viper
#

like, you should be learning kinematic rigidbodies first, which are rigidbodies that go exactly where you tell them to go

undone prism
hard viper
#

yes

#

which totally changes how it works

undone prism
#

ohhhhh k

#

now i get what you mean

#

i didnt know that isKinematic off meant that it was a dynamic rb

#

but in that case i have used dynamic rb plenty of times before

heady iris
#

i saw a neat video about the basics of car physics recently

undone prism
heady iris
#

it does not use unity physics at all

#

(at least, not for calculating how the car behaves)

rigid island
#

^^vid i based a controller on, very good explanation

hard viper
#

there are different ways, but you need to learn more before you start coding anything

#

i’m surprised your professor taught you jack shit about this, and just threw you to the wolves

#

“go make a car”

undone prism
#

nah that isnt really how my school works tho. we have 10 weeks to make a game in groups of 3-5 people and we chose a race game

#

also isnt my first days with rigidbody's. so i think i can make it work

undone prism
#

it only looks like a shit load of work to make it work realisticly

civic isle
#

i dont think you should follow a youtube tutorial for the base of your school project lol

#

unless the professor doesnt care

lethal rivet
#

I'm debating between two different approaches to an Item system for a survival game I'm working on.
There are many different types of items, and a good amount of them have unique functions which will need to be hardcoded. I am wondering if I should have

Unique Class for every item type

  • Can hardcode the unique function into the class, very readable, but bloated
  • Will result in a lot of class files which are just the default file, repeating a lot of boilerplate
  • LogItem, AxeItem, WoodItem, etc...

Or

Have generic Item class differentiated by an Enum

  • For what I am planning, I can handle the unique functions of items outside of the item itself, with a manager script.
  • Probably less readable.
  • Will rely on Unity prefabs
  • A little less safe because of the mutability of Item class instances.
  • Item and possibly inherited classes Tool, Consumable, etc

Anybody have similar experience they can share to help me decide? Thanks!

undone prism
# civic isle unless the professor doesnt care

the last time i saw our teachers care about anything is when the coffee macine broke so im not to worried about that. i only see a lot in that video what could cause issues when wanting to make it realistic. so i dont really know if i even want to go for that approach. on the other hand the wheel colliders have been irritating me so much right now that it does look really tempting.

lean sail
lethal rivet
#

Just to clarify, ScriptableObject in place of what?

#

I've tried to learn about them like 4 times and I always get confused 😅

lean sail
#

It's the same use case as the enum. An enum would just give you a way to serialize it in inspector. You have your item enum exposed in inspector, then look up the actual class you want to create an instance of

lethal rivet
#

I see. Thank you for the insight!

lean sail
# lethal rivet I see. Thank you for the insight!

One thing I will say though, is the scriptable object route is also somewhat a pain. Right now I'm somewhat doing what I suggested, although my items can affect stats and can have unique functionality. Affecting stats is easy, but this gives me actual reason to use scriptable objects because I can assign those numbers in inspector. I can reuse an items functionality with different stats.
In your case, if you're really just creating 1 instance of an SO then it might become a pain. You'll end up creating 2 scripts per item, 1 for SO and 1 for the item, plus the actual instance of the SO.

#

Small rant done

lethal rivet
#

Yeah I totally understand, I did take this approach in the past (although pretty rudimentarily) and I had a similar issue where I needed a lot of file system overhead to make my items work. They were very efficient at runtime because of it, but very inefficient in terms of development time.

viral wagon
#

I got weird problem, I made assembly definition for unit testing. But I came to the conclusion delete all of these stuff including assembly definition and unit test codes. After that all is deleted, I still got error: TypeLoadException: Could not load type '.CharacterStatsManager' from assembly 'AssembleDefinitionTesting'. How I could fix this? That CharacterStatsManager is also deleted, its old code...

heady iris
#

perhaps restart unity

celest iron
#

What is the difference between IJobFor and IJobParallelFor? The documentation makes them sound the same, but with slightly different methods?

prisma yacht
#

hey I made a game that uses a python script to capture webcam feed and then pass it to unity

#

is there a way to build the script with the game?

#

or should I build the unity game and then compile the script to exe

#

and just make the python exe call the unity game exe

simple egret
#

The latter imo, not everyone has the python runtime installed on their computer

heady iris
prisma yacht
heady iris
#

ah, I see

kindred otter
# celest iron bump

IJobs don't have to be run in parallel. You could schedule them to be run sequentially, i guess that's the main difference.

celest iron
#

IJobsFor, you mean?

kindred otter
celest iron
#

And what does it means to run in the main thread?

#

Like, it won't create a new worker thread?

kindred otter
celest iron
#

Ok ty

#

So essentially it will be like a c# task?

kindred otter
celest iron
#

So, the IJobFor has a method called Run() that, according to the documentation, allow the job to "run on the main thread".

#

I'd like to know what that means

kindred otter
celest iron
#

I was confused because "why use job if not to multithread"

#

That clarifies it

kindred otter
#

When you call Schedule() instead, those jobs will usually land on seperate worker threads, but might end up on the main thread too. For this reason unity also recommends to have those jobs finish in under 1 frame.

knotty sun
celest iron
#

Oh, I see

rain lava
#

I have problem about walking sound effects. If I dont leave key, sound doesnt play i used both input.getkey and getkeydown commands

#

If you dont leave key it doesnt play

#

I didnt have this problem for mouse click, it directly plays

#

footstep is reference for class right one

simple egret
# rain lava

You can use just audioSource.PlayOneShot(footstepSound); to simplify down that big block of code in void Step().
In void Update(), walking will always be false because you re-declare it each frame. Visual Studio signals that walking = true; is unnecessary because the variable isn't read afterwards.

rain lava
#

tried first

simple egret
#

You need to add a delay between plays, because here you're playing a footstep sound once per frame

merry stream
#

so Im starting to have a lot of different object pools in my scene (enemy, projectile, damage numbers, etc) and each have their own gameobject singleton. Is there a better way to handle all these pools?

celest iron
#

Probably the factory pattern

merry stream
#

well im not creating the pools at runtime

latent latch
#

EnemyManager.Instance.GetEnemyFromPool()
ProjectileManager.Instance.GetProjectileFromPool()
DamageNumbersManager.Instance.GetNumbersFromPool()

#

or my prefered way:
GameManager.Instance.EnemyManager.GetEnemyFromPool()
GameManager.Instance.ProjectileManager.GetProjectileFromPool()
GameManager.Instance.DamageNumbersManager.GetNumbersFromPool()

dark kindle
#

i make script that ping servers using GET, but it take me more less 50 seconds for it to complete:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class Pinger1 : MonoBehaviour
{
    bool[] online = new bool[50];

    void Start()
    {
        StartCoroutine(PingAll());
    }
    
    public IEnumerator PingServer(int index)
    {
        using (UnityWebRequest uwr = UnityWebRequest.Get($"http://sub{index}.domain.net:8000"))
        {
            uwr.timeout = 1;
            yield return uwr.SendWebRequest();
            switch(uwr.result)
            {
            case UnityWebRequest.Result.ConnectionError:
                online[index] = false;
                Debug.Log($"error: {uwr.error}");
                break;
            case UnityWebRequest.Result.DataProcessingError:
                online[index] = false;
                Debug.Log($"error: {uwr.error}");
                break;
            case UnityWebRequest.Result.ProtocolError:
                online[index] = false;
                Debug.Log($"error: {uwr.error}");
                break;
            case UnityWebRequest.Result.Success:
                online[index] = true;
                Debug.Log($"success: {uwr.downloadHandler.text}");
                break;
            }
        }
    }
    
    public IEnumerator PingAll()
    {
        string list = "";
        for(int a = 0; a < online.Length; a++)
        {
            Coroutine c = StartCoroutine(PingServer(a));
            yield return c;
            list = list + $"{a}: {online[a]}; ";
        }
        Debug.Log($"Ping complete: {list}");
    }
}
#

And result is:
Ping complete: 0: False; 1: True; 2: False; 3: False; 4: False; 5: False; 6: False; 7: False; 8: False; 9: False; 10: False; 11: False; 12: False; 13: False; 14: False; 15: False; 16: False; 17: False; 18: False; 19: False; 20: False; 21: False; 22: False; 23: False; 24: False; 25: False; 26: False; 27: False; 28: False; 29: False; 30: False; 31: False; 32: False; 33: False; 34: False; 35: False; 36: False; 37: False; 38: False; 39: False; 40: False; 41: False; 42: False; 43: False; 44: False; 45: False; 46: False; 47: False; 48: False; 49: False;
Which is correct. How can I make it faster while ensure I get this list correctly?

leaden ice
dark kindle
#

thank

leaden ice
#

This might work???

        string list = "";
        List<Coroutine> coroutines = new();
        for(int a = 0; a < online.Length; a++)
        {
            Coroutine c = StartCoroutine(PingServer(a));
            coroutines.Add(c);
            list = list + $"{a}: {online[a]}; ";
        }

        
        foreach (Coroutine c in coroutines) yield return c;
        Debug.Log($"Ping complete: {list}");```
dark kindle
#

i will take look i appreciate suggestion

fallen lotus
#

Anyone know why this code isn't triggering? I have this in the update method. trying to learn the new input system.

if (playerInputActions.Player.Interaction.WasPressedThisFrame())
{
    Debug.Log("Inside of the interaction if statement");
    interactable.Interact();
}
#

Im pressing F and nothing happens

leaden ice
fallen lotus
#

ill get back to you

#

that was it 🤦‍♂️

#

thank you @leaden ice

latent latch
#

the elusive Enable()

#

strikes again

fallen lotus
#

it always does bro

#

this is my first time with the new input system

fallen lotus
#

i saw another value which was
playerInputActions.Player.Interaction.triggered;
and I wasn't sure if that was the correct way

leaden ice
#

I mean there are many correct ways

#

not just one

#

triggered would also be correct here

#

triggered is equivalent to WasPerformedThisFrame() and there are subtle differences between that and what you have, but with the way your action is set up, they are identical

merry stream
#

was wondering if there was a better way than using singletons

latent latch
#

GameManager is my only singleton

#

well, either way you can just child the singletons under GameManager

#

collapse when you need a manager

merry stream
#

so the only way is with a singleton?

#

i just dont like using them if I dont need to

latent latch
#

Well, take a look at my example again. It's one singleton

#

that's all you need if you design it as such

fallen lotus
merry stream
#

so you just have all your object pool scripts on your gamemanager gameobject which some GameManager script holds references to?

latent latch
#

pretty much. It's the manager of managers

#

(but who manages the manager of managers?!)

merry stream
#

thats why i dont like singletons that much lol

#

the age old question

latent latch
#

It's either bind the gamemanager reference to all your scripts, or just use the static accessor

#

I choose to be lazy

merry stream
#

same thing in the end really

#

does unity give a script u name GameManager a custom image lol

merry stream
latent latch
#

if I want to insert stuff into them from the editor, yes

#

if you're pooling monos, then it's probably going to be on the scene anyway

merry stream
#

yeah since it needs to instantiate

#

is there anyway to subscribe to SceneManager.sceneLoaded without having your function return some UnityAction<Scene, LoadSceneMode>

leaden ice
#

it shouldn't return that

#

it should be that

#

that's a delegate type

#

That means it needs to take a Scene and a LoadSceneMode as paramters

#
void MyMethod(Scene s, LoadSceneMode mode) {
  // blah
}

void Subscribe() {
  SceneManager.sceneLoaded += MyMethod;
}```
merry stream
#

ah i see

leaden ice
#

I guess you were trying to do this??

UnityAction<Scene, LoadSceneMode> MyMethod() {
  // some stuff
  return null;
}

void Subscribe() {
  SceneManager.sceneLoaded += MyMethod();
}```
That's not quite correct
merry stream
#

yeah, its fine with the first example

leaden ice
#

That will just do the "some stuff" once as you subscribe and do nothing else

merry stream
#

is sceneLoaded called after start?

leaden ice
#

you mean after Start for... the objects in the new scene?

merry stream
#

yeah

leaden ice
#

Almost certain it's not

merry stream
#

hm, im trying to have some persistant singleton find the player when the scene changes

#

will that not work then?

leaden ice
#

why not just have the player register itself with this singleton in Start?

#
// In the player script
void Start() {
  MySingleton.Instance.RegisterPlayer(this);
}```
merry stream
#

good point

dark kindle
#

@leaden ice so i ran script and it was still taking 50 sec. what i did was i modify your suggestion and use yield return new WaitUntil(() => responded >= 50); then print the list. In PingServer() at each case I made responded increment by 1 in order to work

merry stream
#

should I use a persistant singleton that moves between each scene or just copy a singleton in each scene for my game manager?

dark kindle
#

i sure http is 100% chance either result in error or success

#

but if not then what idid might not be good

fast dune
leaden ice
quartz folio
leaden ice
fast dune
#

thanks!

#

how inefficient is to do that kind of thing (e.g wireframe effect with LineRenderer) within a script compared to a shader?

#

like, actual games will probably never do something like that?

quartz folio
#

Very inefficient

merry stream
#

to use vfx graph, do I have to instantiate an empty game object with the effect? (ie object pool it) or is there a more efficient way

leaden ice
merry stream
#

so go the object pool route?

leaden ice
#

I don't see how an object pool is relevant

#

unless you need lots of reusable elements of the effect

merry stream
#

for something like a death effect

#

the enemy can't play the effect since it will be destroyed no?

leaden ice
merry stream
#

im not familiar with either the old ParticleSystem or Emit

#

so a single gameobject with VisualEffect on it can create effects throughout the whole scene?

#

even at the same time

leaden ice
#

yep

#

For example on the right side of this screenshot there's a custom event which causes some particles to spawn

merry stream
#

im confused, the visualeffect mobo asks for a asset template which seems like a specific vfx

leaden ice
#

yes a specific vfx

#

Do the enemies have different death effects?

merry stream
#

no, so I need a different gameobject for each effect

leaden ice
#

They all have the same death effect?

merry stream
#

yeah its just some blood explosion

leaden ice
#

then you only need one for the whole scene

merry stream
#

okay then say I add some hit particles

#

i need another for that effect?

leaden ice
#

if it's a different effect yes

merry stream
#

okay makes sense

#

from the enemy script, how do I get it to play the effect at the location?

leaden ice
#

It's kinda hard to explain if you're not experienced with VFX Graph yet... lemme see if I can find a tutorial

#

and read that in the graph

latent latch
#

vfx graph is bestest

merry stream
#

im still confused, it seems like you do need to object pool still?

latent latch
#

particle systems no, but gameobjects yes

merry stream
#

what do you mean?

latent latch
#

there's a few ways you can do it

merry stream
#

if it was something like a shoot fx, it could just be childed to the player or what not

latent latch
#

SingleSystem vs multiple systems like particle system way

merry stream
#

but since its a death effect, the enemy will be destroyed along with the vfx

leaden ice
#

the VisualEffect wouldn't be a part of the enemy object

merry stream
#

what do I pass into SendEvent though?

merry stream
#

i read the docs u sent

#

but i can't seem to figure it out

leaden ice
#

You pass the name of the event (you would make an event like "SpawnBloodExplosion") and the position you want to pass in (the position where the enemy died)

merry stream
#

this event?

leaden ice
#

no

#

a custom event

latent latch
#

it's good for predicted vfx but if it's constantly updating cpu side via physics there's some extra work you need to do

merry stream
#

nah its just a flipbook death effect

latent latch
#

graphic buffers is useful for moving projectile gameobjects that can't be predicted in the gpu

merry stream
#
        attritube.SetVector2("Position", transform.position);
        GameManager.Instance.DeathFX.SendEvent("SpawnDeathEffect", attritube);```
#

like this?

latent latch
#

looks like it

merry stream
#

not working, hm

leaden ice
#

well did you set up the graph itself properly?

leaden ice
# leaden ice

You need to set the event up like this in the graph and hook it to a spawn system ("MyAwesomeEvent" example)

#

that's too blurry to read

#

even when I "open in browser"

merry stream
leaden ice
#

that's doing 1 particle per second

merry stream
#

now its not even playing

leaden ice
#

Before trying your code

#

play with the "Send" button in the graph on the event

#

to make sure it works there

#

What position are you spawning the particles at right now?

merry stream
#

just at the enemy position

#

but i didn't realize once you made a custom event the Play button wouldnt work

#

it still plays but there are some artifacts it seems

#

not sure why

leaden ice
#

right now just try to get it to spawn at 0,0,0 when the event happens

merry stream
leaden ice
#

you might be experiencing an issue with the bounds

leaden ice
#

in the grapoh

#

how are you getting the position

merry stream
#

no idea

#

lol

leaden ice
#

so you're probably not at all

merry stream
#

yeah

leaden ice
#

it's probably being ignored

#

which is ok for now

merry stream
#

ah yeah, its all being played at 0,0,0

leaden ice
#

Is that working then at least?

merry stream
#

yeah

#

do I do something like this then?

leaden ice
#

I think you might need to... define the custom attribute in the graph somewhere?
It's a little fuzzy to me

#

but this would be your custom position attribute

merry stream
#

still not working, hm

leaden ice
jagged snow
#

I have a scriptableobject that doesnt seem to be saving whenever I restart my unity. It seems to save all the values in and out of play mode just fine, however all the values are reset after closing the client...The values are just Vector3 and Quaternion

leaden ice
#

Are the values serialized?

swift falcon
#

How can I make a currency system in 3d?

leaden ice
swift falcon
#

Yes

leaden ice
#

Without further details, that is a "currency system"

jagged snow
# leaden ice Are the values serialized?
    {
        _dataSO.Save(_gunTransform.localPosition, _rightHandTarget.localPosition, _rightHandTarget.localRotation, _leftHandTarget.localPosition, _leftHandTarget.localRotation, _rightElbowTarget.localPosition, _leftElbowTarget.localPosition);
    }```
```    public void Save(Vector3 gunPos, Vector3 rightHandPos, Quaternion rightHandRot, Vector3 leftHandPos, Quaternion leftHandRot, Vector3 rightElbowPos, Vector3 leftElbowPos)
    {
        Debug.Log("DATA SAVED");
        GunLocalPosition = gunPos;
        RightHandPos = rightHandPos;
        RightHandRot = rightHandRot;
        LeftHandPos = leftHandPos;
        LeftHandRot = leftHandRot;
        RightElbowPos = rightElbowPos;
        LeftElbowPos = leftElbowPos;

    }```

public class WeaponIKDataSO : ScriptableObject
{
[HideInInspector] public Vector3 GunLocalPosition;
[HideInInspector] public Vector3 RightHandPos;
[HideInInspector] public Quaternion RightHandRot;
[HideInInspector] public Vector3 LeftHandPos;
[HideInInspector] public Quaternion LeftHandRot;

[HideInInspector] public Vector3 LeftElbowPos;
[HideInInspector] public Vector3 RightElbowPos;```
swift falcon
leaden ice
merry stream
#

is "overwrite" and "source" correct? still spawning at 0 0

leaden ice
#

not sure

#

what other options are there

#

also is that attribute name correct?

jagged snow
leaden ice
#

That's probably the built in position attribute?

merry stream
#

overwrite add multiply blend, then source/slot

#

"use Get Source Attribute Operators or Inherit [Attribute] Blocks."

#

in that doc

jagged snow
leaden ice
#

This is, I assume, for some kind of editor tooling?

spring creek
# swift falcon Do you have a tutorial with more details

I mean, they would just be sending your the first link from googling "unity currency system"
You can search that yourself.
If you give ANY amount of details for what you want, we could suggest something more helpful. But so far you have said nothing, and praetor gave the best answer so far

jagged snow
#

That did it, setdirty() works

#

I'll use this whenever I want to save scriptabledata at runtime now thanks!

leaden ice
#

Yep - note of course this only works in the editor

leaden ice
leaden ice
#

Do you have Sprite Mode set to Single or Multiple?

#

Also this is not a code question at all

pine condor
#

Hi, with debug.log, could i pass a specific variable on an object as the context, to highlight the specific variable in the editor to show which one has the error? how would i do this?

soft shard
# pine condor Hi, with debug.log, could i pass a specific variable on an object as the context...

You can pass a object as the second param, but AFAIK you cant really highlight a variable, you can use nameof on your variable though, for example: Debug.Log($"value of {nameof(someVar)} is: {someVar}", this);, if that was on a Mono script on some object, that object would get highlighted ("this", referring to the script attached to the object) with the name of "someVar" and its value, if that is what you might be referring to

pine condor
slim gate
#

Whats a better way to handle attacks against enemies, more specifically preventing an enemy to get hit by the same attack twice?

  • ImmunityFrame: When an enemy is hit I set a bool "InIFrame" to true and start a Coroutine to set it to false after a short time. While this bool is true the enemy cant be hit. A problem here is if I want to add faster weapons that potentially with alot of upgrades could end up with an attackspeed that is faster than the Immunity time, which would get very frustrating. My game is also multiplayer so the IFrames would be only local for each client so you dont prevent other players from hitting an enemy.
  • Random ID for each individual attack: Each attack gets a random ID with something like Random.Range(int.MinValue, int.MaxValue). If an enemy has already been hit by an attack with this id it wont register. I dont know how likely it would be here to randomly generate the same value on 2 different attacks? Maybe do something with not a random value but time since the game started/ current time?

I guess both are okay? Am I missing something? Which is a better idea or does it just down to the individual needs?

fickle moth
slim gate
#

Just once

#

And some enemies consist of multiple colliders that would all trigger OnTriggerEnter

#

Or is there something I am missing?

#

Isnt an IFrame/ ImmunityTime pretty standard?

fickle moth
#

and if it is crucial to your game that you retain that function i would say set a maxInv float that represents the max amount of time an enemy can be invincible and then when you hit an enemy you set a bool isHit = true which stops it from being hit again and then you can start incrementing a currentInv float to track how long its been since going inv then when it hits max you can reset the bool isHit to false and reset the currentInv float to 0 or the max if you want to decrement it instead

#

this will allow for a looping logic

#

you should have sword collisions in an Ontrigger or OnCollsion method imo

#

they only get called once per collison and you can specify enter , exit , stay

slim gate
#

Yeah but for each collider on the enemy right?

fickle moth
#

oh your enemy has multiple colliders?

slim gate
#

What ive been told is to do OverlapBox or BoxCast

fickle moth
#

in that case make a collider manager and have themall contribute to the isHit

slim gate
slim gate
fickle moth
#

happy coding!

slim gate
#

I also could use a PoligonCollider instead of several Basic ones I guess?

#

But idk how much worse that is for performance

fickle moth
#

you can really use whatever you want , and if your game is 2D dont worry about performance imo

#

majority of the phones could run anything we could make in 2d imo

slim gate
#

yeah i guess

fickle moth
#

you arnt limited to just 2D objects in a scene if you havent figured that out yet

slim gate
#

nono I know)

#

But i havent had the need for anything 3d

#

in my current game that is

fickle moth
#

same here rarely use it

rocky pumice
#

I am making a 2D Platform Fighter and I'm trying to track weather or not my player is grounded by using Physics2D.BoxCast(). This works pretty well, however the BoxCast seems to not perfectly synchronize with the players movement. By rapidly flipping the Contollstick left and right and spamming jump near a wall, you can wall jump, which is not supposed to happen. When running into a wall there seems to be a few frames, where the box will clip inside the wall. Here are 2 videos to demonstrate this. The green lines were made with Debug.DrawRay() and are supposed to represent the box. Here is the code for my Movement, Jump and IsGrounded: https://gdl.space/govizotari.cs. Help would be greately appriciated :)

bright comet
# fickle moth and if it is crucial to your game that you retain that function i would say set ...

The last time I had to solve this problem, the issue was as follows: An attack had a certain duration and hit all enemies coming into contact with my sword. To detect colliders, we used Physics.overlapSphere() within a coroutine. All hit enemies were added to a list. Before hitting an enemy, we checked that it hadn't already been hit (by checking the list). At the end of the attack, the list, contained within the coroutine, was destroyed.

I don't think this is the most performance-optimized way, but for usability and bugs, this system was perfect.

fickle moth
bright comet
rocky pumice
outer brook
#

I know you can have music playing through scenes with donotdestroyonload but how would you be able to it when playing through a set of scenes but not all of them?

fickle moth
fickle moth
slim gate
#

I will rethink my approach to see what works best)

fickle moth
fickle moth
bright comet
lean sail
tawny elkBOT
bright comet
fickle moth
#

discord recommended uploading as file

fickle moth
slim gate
fickle moth
#

its just a pain sometimes

knotty sun
fickle moth
#

can someone help me with my TMP_Dropdown issue now ? 😂

bright comet
#

I do not work on 2D with unity, but for 3D, I stopped to use raycast to prefere sphereCast in some case

fickle moth
fickle moth
rocky pumice
bright comet
fickle moth
fickle moth
rocky pumice
fickle moth
thin spruce
#

Hi, im really stumped on this, i want to be able to detect when an object is visible by a specific camera ('PovCam'), ive tried multiple solutions and nothing works, this is the current code

thin spruce
#

im using a linecast rn, which i think is a raycast between 2 points

bright comet
fickle moth
#

well actually no there isnt a script modifying each item

the script is only changing the preview color box and the background color

bright comet
fickle moth
#

is there a cone collider?

bright comet
#

nope =/

fickle moth
#

lame 😦

rocky pumice
fickle moth
#

ohhhh

placid summit
#

Unusual requirement - I need to write out SVG files - anyone used an API to help do that with Unity?!

fickle moth
#

put on layers

#

make it so only one camera can see specific layers

thin aurora
fickle moth
placid summit
fickle moth
thin spruce
#

better formatting

fickle moth
#

What does this pos represent

thin aurora
placid summit
thin aurora
#

Or the if-else?

thin spruce
thin spruce
thin aurora
fickle moth
placid summit
fickle moth
rocky pumice
outer brook
dire crown
#

Hello can someone help me modify BlurValue so that calculatedSize matches expected Size?

using UnityEngine;

[ExecuteAlways]
public class calculator : MonoBehaviour
{
    public float size;
    public float expectedSize;
    public float calculatedSize;
    public float difference;

    // Update is called once per frame
    void Update()
    {
        int EffectSize = Mathf.Max(1, Mathf.FloorToInt(size));
        float ExtraSize = Mathf.Clamp01(size-EffectSize);

        calculatedSize = BlurValue(EffectSize, ExtraSize);
        float total = EffectSize+ExtraSize;
        expectedSize = (total*2+1) *(total*2+1);
    }

    public static float BlurValue(int EffectSize, float ExtraStrength){
        float average = 0;
        for(int z = -EffectSize; z <= EffectSize; z++){
            for(int w = -EffectSize; w <= EffectSize; w++){
                average += 1;

                if((w == -EffectSize || w == EffectSize) && (z == -EffectSize || z == EffectSize)){
                    average += ExtraStrength*ExtraStrength;
                } 
                else
                if(w == -EffectSize || w == EffectSize){
                    average += ExtraStrength;
                }else
                if(z == -EffectSize || z == EffectSize){
                    average += ExtraStrength;
                }

            }
        }
        return average;
    }  
}```
#

I don't know what am i missing or doing wrong. Basically it's calculating the area in a discrete way (to make sure for othe processes so it's normalized)

slim gate
#

I just learned about MonoBehaviour.InvokeRepeating for the first time. It seems very nice but I have never seen anyone use it over Update(). One thing i could imaging this being good for is for example on each enemy to check for the closest player every second instead of every frame. Is this a good idea? Can I use this instead of Update() on everything that I need regularly, but not every frame, or is there an argument/ reason against it?

mellow sigil
#

It's an old method from before coroutines existed. Coroutines are better in every regard

steady moat
dusk apex
slim gate
#

My first guess would be like this

#

But it feels weird to restart coroutines this often. Is this not bad for performance

mellow sigil
#
private IEnumerator CheckClosestPlayer(){
    while(true)
    {
        yield return new WaitForSeconds(1);
        // Logic
    }
}
dusk apex
#

An infinite while loop with a yield statement.
Make sure to cache the yield instruction prior to the loop

slim gate
#

Coroutines will stop when Gameobject is destroyed I assume

slim gate
dusk apex
slim gate
#

Oh i didnt know thats possible! Very neat!

#

I can use this in a few places in my code already

#

Thanks alot!

dusk apex
slim gate
#

Oh yeah I saw that before

#

Will come in handy for the enemies

#

Then Ideally I would spawn my enemies wth small delays so this doesnt fire every second on all enemies but spread out throughout the second

#

Or is there a better way to achieve this?

dusk apex
#

ECS but that'd be an entirely different beast.

#

Other than that, for what you're doing it should be fine.

dusk apex
slim gate
#

Yeah I will have to see if its a good idea in my case

#

My game is multiplayer so that complicates it a bit

#

But I dont have so many enemies that it would become a problem I hope

sudden hinge
#

I want to put in an URL and then have Unity download each file in the directory.
Does anyone know how to do this?

I cannot figure it out, as when I GET the url path it just gives a blank string in return

sudden hinge
#

Yep, used it a lot in the past, but cannot get all files in the serverdirectory

#
 private IEnumerator DownloadDirectoryContents(string directoryURL)
 {
     // Make a UnityWebRequest to download the directory listing
     UnityWebRequest request = UnityWebRequest.Get(directoryURL);

     Debug.Log("getting url: " + directoryURL);

     // Wait for the request to complete
     yield return request.SendWebRequest();

     // Check for errors
     if (request.result != UnityWebRequest.Result.Success)
     {
         Debug.LogError("Failed to download directory: " + request.error);
         yield break;
     }
     Debug.Log("got url: " + request.downloadHandler.text); //BLANK
     // Split the response into lines to get the filenames
     string[] lines = request.downloadHandler.text.Split('\n');

     // Call ImportData() for each file
     foreach (string line in lines)
     {
         string fileName = line.Trim();
         if (!string.IsNullOrEmpty(fileName))
         {
             ImportData(directoryURL + "/" + fileName);
         }
     }
 }```
dusk apex
#

Maybe show what you've tried so they can help you better

sudden hinge
#

The code after //BLANK is not tested. First I need to get all files in the directory, which is where I am getting stuck

knotty sun
#

you would probably need to use ftp protocol rather than http as directory listing is usually disabled

sudden hinge
#

Ah okay
I will need to look into that, as I am not sure if that will be the most flexible solution. Maybe I will just type out the full file name for the current prototype

rigid island
#

maybe hmm been a while since I touched folders on webrequest
You could just zip the contents too

sudden hinge
#

Not too bad of an idea to zip it yeah

knotty sun
#

may be better writing your own backend API's to do this

sudden hinge
#

Thanks for all the ideas, I'll discuss with the team and start working on it 👌

narrow ore
#

Why everybody sheeting on those messages?

gray mural
stoic ledge
#

Is there a way to selectively preload localization tables?
E.g. preload only string tables, while avoid preloading asset tables.

If not possible out of the box, how can I selectively preload those myself?

sweet niche
#

Can anyone tell me why this code would make my Rigidbody object "jump" upward on the Y axis while moving "forward" on the X Axis?
Rigidbody.AddForce(new Vector3(30,0,0), ForceMode.Impulse);

knotty sun
#

because your transform is rotated

sweet niche
#

Just checked and No, rotation is all 0's

leaden ice
sweet niche
#

Yeah, that is what I was thinking. But my ground is just flat. I will say, that if I increase my normal movement speed than my character start to move upward slightly as the speed increases

#

Not sure if I have something increasing Y axis for some weird reason

knotty sun
sweet niche
#

one second

#
    {
        RaycastHit[] hits;

        hits = Physics.RaycastAll(new Vector3(transform.position.x, transform.position.y + .5f, transform.position.z), Vector3.down, battleGroundMaskID);

        for (int i = 0; i < hits.Length; ++i)
        {
            RaycastHit hit = hits[i];
            if (hit.transform.tag == "battleFloor")
            {
                //check distance
                if (hit.point.y + .1 >= transform.position.y)
                {
                    battleGrounded = true;
                    knockBackFloorYVal = transform.position.y;
                    break;
                }
                else
                    battleGrounded = false;
            }
        }

        if (battleGrounded)
            RB.drag = groundDrag;
        else
            RB.drag = 0;
    }

    void battleSpeedControl()
    {
        Vector3 flatVel = new Vector3(RB.velocity.x, 0f, RB.velocity.z);

        //limit velocity if needed
        if (flatVel.magnitude > battleSpeed)
        {
            Vector3 limitedVel = flatVel.normalized * battleSpeed;
            RB.velocity = new Vector3(limitedVel.x, RB.velocity.y, limitedVel.z);
        }
    }

    private void PlayerBattleMovementFU()
    {
        if (inMainBattleMenu)
            return;
        if (battleBlockFlag)
            return;
       battleSpeedControl();
      battleRigidBodyCheckGrounded();
        if (playerControl == globalControllerScript.PlayerControl.player) //player controlled
        {
            battleMoveDirection = new Vector3(inputMovement.x, 0, inputMovement.y);
            RB.AddForce(battleMoveDirection.normalized * battleSpeed * (battleSpeedMultiplier), ForceMode.Force);
        }
    }```
lofty summit
#

Is there any advantage to make a singleton based in monobehaviour if I don't need any of that behaviour in my class? 🤔

leaden ice
#

You can put it in your scenes and reference it via the inspector, and run coroutines on it

#

other than that, no

lofty summit
#

the coroutines one I hadn't considered 🤔
thanks ❤️

heady iris
#

Being able to run coroutines is handy, yeah

upper pilot
#

    [field: SerializeField] private TextMeshProUGUI AttackText { get; set; }
    [field: SerializeField] private TextMeshProUGUI DefenseText { get; set; }

Do you append your properties with "Text" even tho the type should be enough to clarify what it is?

#

I am thinking if I should abolish this 😛

leaden ice
upper pilot
#

oh Label I like it, tho in my case its AttackValue, would Label still count?

leaden ice
#

¯_(ツ)_/¯

#

AttackValueLabel?

#

AttackStatLabel?

upper pilot
#

I guess TmPro might imply a lot of things like text formatting, so adding Label/Text might not be a bad thing.

late lion
upper pilot
#

yeah the class is CharacterAttributeUI or something

#

😄

#

Btw do you ever use plural in your class names?

#

CharacterAttributesUI -> Attribute vs Attributes

upper pilot
#

Or is it an overkill?

latent latch
#

if it's a simple project then stats can be as simple as enums with a dictionary of values pointing to each enum entry

#

but if you do have stat modifiers, then making a system of containers to keep track of everything could be of use

upper pilot
#

I do have Attributes class to return "total" of anything.
But my question is mostly about the UI, if its worth adding another UI class for each stat separately.

latent latch
#

Eh, I'd just have a StatsUIManager if needed

upper pilot
#

Yeah thats what I have, it updates all stats

latent latch
#

looks fine to me

upper pilot
#

great

#

So this might be complicated topic or maybe even not worth it.
But is there a way to create a helper function for this type of script?

    public void Init(Character character)
    {
        Character?.ExperienceManager.OnAttributeChange.RemoveListener(UpdateAttributes);
        Character = character;
        Character.ExperienceManager.OnAttributeChange.AddListener(UpdateAttributes);
    }

And second script with same logic:

    public void Init(Character character)
    {
        characterAttributeUI.Init(character);

        Character?.HealthSystem.OnHealthChange.RemoveListener(UpdateHealth);
        Character = character;
        Character.HealthSystem.OnHealthChange.AddListener(UpdateHealth);
    }

They subscribe to different events etc, but their logic is the same.

#

Something along the lines of:

public void Init(Character character)
{
  HelperFunctions.ChangeSubscription(Character?.HealthSystem, character.HealthSystem, UpdateHealth);
  HelperFunctions.ChangeSubscription(Character?.ExperienceManager, character.ExperienceManager, UpdateAttributes);
}

I think this could work, but idk if its worth it.

thick terrace
#

it's awkward to try and write a generic type-safe helper method for this because afaik you can't constrain a generic parameter type to be a delegate

latent latch
#
[InfoBox("Values Per StatModifier", EInfoBoxType.Normal), Header("Flat Increased Values"), Range(1, 100),
field: SerializeField] public int Health{ get; private set; } = 1;
//causes error

Anyone have any suggestions how to fit attributes nicely? They seem line sensitive, so you can't split them up that well

leaden ice
#

Normally I give them their own brackets and lines:

[field: Range(1, 100)]
[field: SerializeField]
[field: Header("Flat Increased Values")]
[field: InfoBox("Values Per StatModifier", EInfoBoxType.Normal)] 
public int Health{ get; private set; } = 1;```
latent latch
#

hmm seems some conflict somewhere

#

I think it's because of field: SerializeField

leaden ice
#

what's teh code look like and what's the error say?

latent latch
leaden ice
latent latch
#

ahh, I understand

leaden ice
#

they only work on fields, not properties

latent latch
#

Right, because when it's in its own box it has the field tag, as opposed to one field tag when combining them all

#

ty

leaden solstice
#

Now you have multiple field: might just write private int health; and save typing 😄

high condor
#

where can i download older versions of cinemachine?

leaden solstice
high condor
#

where?

leaden solstice
# high condor where?

If it does not show up you can specify the version you want in Packages/manifest.json

high condor
#

o wait nah thats wrong, im not sure which file im supposed to be in. i cant find a file called manifest

leaden solstice
leaden solstice
high condor
#

the file i had edited was some random package.json

soft shard
upper pilot
#

I also had similar concern of typing text.text before

final sedge
#

Hello, im new here amm and i dont know if I can do a question?

undone prism
#

so im making a race game and i wanted to try and make my own wheel collider because i had some issues with the unity one and this seemed like a fun and usefull thing to do. i have started with making the suspension of the car. the way i make this work is by having my wheels as child of my car. i then get a start value and use that to modulate my car up and down with addforce. this works nicely to a certain point. when you get on slopes or things like that the car launches into the air. i cant find why its so unpredictable and what im doing wrong. https://gdl.space/ejukepires.cs this is my script. other coding tips or tricks that could help me are of value to me as well.

devout nimbus
#

Anyone have issues with a List/Array clearing upon entering playmode? There is no code creating a new list or anything. It is private as well so no other class is altering it.

somber nacelle
#

that's not enough info to really diagnose what is going on, a list wouldn't just clear itself for no reason

devout nimbus
#

Oh I think the issue is that I renamed the list and something else is now its previous name. Seems serialization has caused some issues

#
 [SerializeField] private List<GameObject> townsPeoplePrefab; 

    public Transform shopPosition;
    public List<GameObject> townsPeople;

    [Header("Game References")]
    [SerializeField] private VampireSpawner vampireSpawner; //later will have to inject and shit


    private void Awake() {
        Debug.Log("Array has items: " + townsPeoplePrefab.Count);
        //townsPeople = new List<GameObject>();
        Debug.Log("Array has items: " + townsPeoplePrefab.Count);
        StartCoroutine(SpawnTownsPeople());
        Invoke("SpawnMonster", 5f);
    }```
Sorry bunch of random debugs trying to see where its cleared but every log statement says it is 0.
townsPeople was the old name of townsPeoplePrefab
I think clearing that list is what was clearing the other one perhaps
#

//townsPeople = new List<GameObject>();

commenting out this line changes it a bit where it now looks like the townspeople isnt being cleared in the inspector but it is still saying there are 0

#

Might be because of my fast script reloader asset. I think it is improperly recompiling

somber nacelle
devout nimbus
#

Manually recompiling isnt fixing the issue tho. Control+R is how I am doing it but is there a better more extensive way?

somber nacelle
#

but also townsPeople = new List<GameObject>(); would not affect the townsPeoplePrefab variable at runtime

devout nimbus
#

This was an array and the other a list so I don't know why it was giving me issues then too.

somber nacelle
#

again, at runtime that would not have any affect on it. show a screenshot of the inspector outside of play mode

devout nimbus
#

The screenshot I sent was outside of playmode

spark flower
#
                movePosition = targetPlayer.transform.position + new Vector3(attackRange * Mathf.Sign(targetPlayer.transform.localScale.x), 0, 0);

                if (Vector3.Distance(transform.position, movePosition) > settings.moveSpeed) {
                    transform.localScale = new Vector3(Mathf.Sign(targetPlayer.transform.position.x - transform.position.x), 1, 1) * scale;

                    movingSpeed = Vector3.ClampMagnitude(movePosition - transform.position, 1) * Mathf.Min(settings.moveSpeed, (movePosition - transform.position).magnitude);
                    transform.position += movingSpeed;
                } else {
                    if (actionType == ActionType.Power) {
                        StateSet(PlayerState.Strike);
                    } else {
                        if (!reversalAttack && !counterAttack && (TargetPlayer != null) && TargetPlayer.CounterAttack()) {
                            StateSet(PlayerState.Idle);
                        } else {
                            StateSet(PlayerState.Strike);
                        }
                    }
                }```
guys why is the transform.position not changing in this code? the transform.position is not changed anywhere else
somber nacelle
devout nimbus
#

There are two

somber nacelle
#

yes and the one you are checking the count of has no elements

devout nimbus
#

Oh I see those items belonged to the old list I guess it transferred over that makes sense now nevermind

somber nacelle
devout nimbus
#

Since I renamed

spark flower
#

it doesnt have anything

somber nacelle
#

i mean, it does at least have whatever this component is. show the full code

spark flower
#

what do you mean? i checked what code executes and the code in this IF statement is the one that runs, but the position doesnt change
if (Vector3.Distance(transform.position, movePosition) > settings.moveSpeed)

somber nacelle
#

that doesn't prove that nothing else is overwriting the position anywhere

spark flower
#

yeah, it did work before a change but not sure why

fickle moth
#

you will def need to repurpose methods out of it for your own needs

white dew
#

vs code is causing me lots of grief. from what i've learned online, i think it's the intellisense not working. but also, none of my scripts can access other scripts.
solutions i've tried

  • uninstalling and reinstalling vscode and .net
  • deleting project files and having unity regenerate them
  • deleting the entire unity project off of my computer and reinstalling it thru github
  • removing and updating all relevant visual studio unity packages
  • opening it from Assets/Open C# Project

the image attached shows intellisense not working. it's like each script is completely isolated from every other one, including the libraries.
does anyone know what the hecks going on 🙏

somber nacelle
#

make sure that !vscode is configured. if you continue having trouble with it after following all of the steps, you should consider switching to a real IDE that is less likely to randomly break

#

!vscode

tawny elkBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

white dew
#

yeah i've tried that, ill just switch to visual studio then

stoic rain
#

it wont let me launch unity bc i have a pub network how do i fix?

cosmic rain
stoic rain
#

ok mb

hard sparrow
#

Is using scriptableobjects to store relevant data not a sufficient save/load solution? I thought it was, and it when using a scriptableobject to store 'completed levels' it works fine in Unity. But when I build to phone it seems to forget that info when closing and opening the game

somber nacelle
#

changes to scriptable objects do not persist in a build. it only does in the editor because you are changing the serialized values on an asset

hard sparrow
#

So I know json serialization is often the solution for a PC game - is that also the normal save load solution for a mobile game?

somber nacelle
#

yeah

hard sparrow
#

Do you have to encrypt to prevent save cheating on mobile?

#

The game has microtransaction items so

somber nacelle
#

if saves are stored locally then anyone dedicated enough will manage to modify it. the only true way to prevent cheating is to store all that data server side

hard sparrow
#

Hmm... well I still can't even decide where free with micro transactions is better than just charging straight up... do small games with no marketing (assuming they are fun + high quality) make any money with the free with micro transaction model? or does that require economy of scale to do anything

#

guess I should do market research... blegh...

dark kindle
#

if i were publish fast, i would charge in my view, there is less code i need to to inside app

fickle moth
#

Hey all!

Anyone got some tips for an online player counter?

I have one implemented already that ive coded myself interacting with a vps i own which is able to queue requests to increment and decrement the online player count.

works great only 1 issue though if you close the game from task manager it never calls OnApplicationQuit which decrements the online count.

upper pilot
#

How can I use this function:

        instance.GetComponent<Button>().OnSelect(() =>
        {

        });

Trying to detect when a button is selected(it's used for selecting a category of list items, when I "select" different category I want to update a list)

somber nacelle
fickle moth
dark kindle
upper pilot
#

Seems like I digged out forgotten technology, it doesn't seem to be used anymore and I cant google much, other than Select Handler, but I was hoping to do it through my manager class instead of creating a class for a button.

fickle moth
dark kindle
#

i treid fishnet but it too high level for the type gamie i make

fickle moth
upper pilot
fickle moth
upper pilot
#

I want to call a function when a button is selected, but I dont want to attach a script on a button if possible(tho I am doing it now since nothing else works for me :P)

fickle moth
#

thats what i thought

upper pilot
#

I want those buttons to act as category selection in game, to update inventory list with different items based on their category.
Since enums can't be used in the inspector, I have to do something else.

#

Otherwise I'd use EventTrigger

fickle moth
#

may i ask why you dont want the button to have a reference to a script in the onclick method

upper pilot
#

Because I dont want to click a button, I just want to move between buttons with something like arrow keys/d-pad and it should automatically switch categories without having to presss [x] or enter

#

Maybe button is not a right component for it?

fickle moth
#

enums can be used in inspector if you do somethign like this
Public ENUMNAME enumdropdown

public enum ENUMNAME
{
Type,
Type1,

}

upper pilot
#

It cant be used for function calls, at least didnt work for me

dark kindle
#

there may be another function like socket.ConnectedClients to get exact number of clients as alternate but i have to review that

fickle moth
upper pilot
#

I dont understand what do you mean 😐

fickle moth
somber nacelle
#

why are you trying to do this

upper pilot
#

Well, I can achieve what I want by adding a script to a button...I was hoping for a simple solution.

fickle moth
#

are you trying to procedurally generate the buttons?

upper pilot
upper pilot
somber nacelle
#

that's not an answer to the question i asked. what is the actual purpose of this code, what is it supposed to do and why have you decided to use reflection to refer to the list by a string of the variable name

upper pilot
#
    public void RedrawInventory(InventoryCategories categories)
    {
    }

You can't call this function from Unity inspector onClick event.

fickle moth
#

remember nobody cares what the code looks like in the end only the final product

upper pilot
#

I didnt, I just went the route that had to work, I wanted to avoid adding a script to a button.

somber nacelle
#

oh my god

#

did you even bother reading what i asked?

#

no, it most certainly is not

#

at this point, no. because you won't bother providing info on why you've decided to do this specifically or what the goal for this code even is. which is what i was asking about, i do not give a shit about whether this is for your friend, for the president of the united states, for a homework assignment, in order to take over the world, none of that is relevant to the actual code

upper pilot
somber nacelle
upper pilot
#

Idk try to debug it and separate GetType() and GetField() and see which one gives null, then you are one step closer to fixing it.

#

I never used GetType() not sure what it does, does it GetType of your current object/class?

#
Returns
Type

The exact runtime type of the current instance.
somber nacelle
#

i am not asking for any personal details. are you just intentionally ignoring what i'm actually asking about?

#

i was trying to understand the fucking point of the code. not why you decided to sit down at your computer andwrite the code, but what the code is actually trying to fucking accomplish

upper pilot
#

No reason to discuss it any further, maybe you two are not match for each other 😛

somber nacelle
#

then show them this: https://xyproblem.info
and then find out what the code is actually supposed to do because you are currently attempting to solve an issue that makes no fucking sense to even have

upper pilot
#

I kinda agree, I am confused as well.
Is it trying to find an item on a List of Sprites called Hat, by using a string? So its trying to compare object Name(in hierarchy?)

cosmic rain
#

Why can't your friend ask for help then? It's really frustrating when trying to help someone via a proxy without the full context.

upper pilot
#

Well the best we can do to help, is tell you to debug your code like I mentioned and see where the issue happens step by step.

cosmic rain
#

Well, if you don't have a home, just buy it are not on discord, just get on discord.🤷‍♂️

somber nacelle
#

my guy, whatever this is supposed to be solving is what should be discussed, not this. because this is some hairbrained attempt at solving something else. so instead of trying to fix this broken solution that makes no sense to use in any context, we should instead be focusing on the actual problem

upper pilot
#

This code to me looks like some weird complex puzzle with no purpose, but idk maybe thats his assignment.
I doubt you ever use that kind of code in real projects(but I could be wrong)

#

Which is why its hard to help without more info.

cosmic rain
#

This whole situation feels really silly to me.

#

Just tell your friend to get his ass up here instead of running errands for them

upper pilot
#

Tbh when you help people all the time here it can be frustrating sometimes 😄

somber nacelle
#

i'm just absolutely flabbergasted that anyone would answer the questions i asked in the way that you did

upper pilot
#

Not that I spend much time helping <_<

somber nacelle
#

"what is the purpose of this code"
"i'm helping my friend"
"what is the code supposed to do"
"i'm helping with his homework, why do you want my life story just help with my code"

upper pilot
#

Well anyway, I will bring back my question with my attempted solution that I dont like, because it forced me to create a script specifically for this.


public class InventoryCategoryButtonUI : MonoBehaviour, ISelectHandler
{
    [field: SerializeField] private InventoryCategories Category { get; set; }
    public void OnSelect(BaseEventData eventData)
    {
        InventoryUI.Instance.RedrawInventory(Category);
    }
}

This is on a button.

Can I achieve it without having a script directly on a button, but rather use my Manager class and do:

var instance = Instantiate(ButtonPrefab, parent.transform)
instance.getComponent<Button>().OnSelect()//??
#

The issue is mostly there due to enum, each button represents a category which is meant to update List of items based on selected button.

#

Perhaps a Dictionary<InventoryCategories, Button> would do?(Asssuming that I find a way to call a function on button Select)

#

EventTrigger on a button, calling a function in my inventoryUI.Redraw() and then comparing Button instance to dictionary?
Dictionary<Button, enum>

cosmic rain
#

There should be an event you can subscribe to on the button.

somber nacelle
#

OnSelect isn't an event on a Button. but you can use an EventTrigger that will raise an event when OnSelect is called on it by the EventSystem

upper pilot
#

onClick is the only event, oh...what if I add EventTrigger and simply use that in code...

#

let me see that lol

#

No idea how to use that in script, it says that I cant use lambda expression.

#
instance.GetComponent<EventTrigger>().OnSelect(() => { });
#

The reason I cant do it from the inspector is because I have enum(for each category)

#
public enum InventoryCategories
{
    Healing,
    Combat,
    Key
}
#

And there is nothing I can find on google about OnSelect, except ISelectHandler, but that requires a script on a button directly.

cosmic rain
somber nacelle
#

because OnSelect is still not an event there. but the event is in the EventTrigger's triggers list and you can subscribe to it in there

upper pilot
upper pilot
somber nacelle
#

no

#

because that is not the event. that is just the OnSelect method called by the EventSystem

upper pilot
#

So there is no way call this:

instance.GetComponent<EventTrigger>().OnSelect()

I dont understand how this is supposed to work.

somber nacelle
#

i feel like i'm talking at a wall

#

that is not the event

#

that is literally the exact same method you have implemented from the ISelectHandler interface. you do not call that manually. nor can you subscribe to it because it is a method. the event on the EventTrigger is in the triggers list like i already told you

upper pilot
#

I got that, I am trying to understand what its purpose is(OnSelect) since I can call it directly from script.

#

oh

#

thats what I thought, so this is like Invoke()

#
        BaseEventData eventData = new BaseEventData(EventSystem.current);
        instance.GetComponent<EventTrigger>().OnSelect(eventData);

I was just playing with it and this code compiles, not sure what it does tho.
Either way I understand that its not an event like onClick

somber nacelle
#

no, that is the OnSelect method called by the EventSystem, exactly like your OnSelect method for the component that implements ISelectHandler because the EventTrigger implements ISelectHandler

#

congrats on fixing the worst possible way to refer to a variable at runtime 👍
maybe next time you need help it will be with something that actually makes any sense to do

#

and hopefully whatever the fuck you did actually solves the initial problem your "friend" was trying to solve

upper pilot
#

So actually chat gpt did give me a solution, trying to understand how that works tho as this is a new way for me

private void AddOnSelectListener(Button button)
    {
        EventTrigger eventTrigger = button.gameObject.GetComponent<EventTrigger>();

        EventTrigger.Entry entry = new EventTrigger.Entry
        {
            eventID = EventTriggerType.Select
        };
        entry.callback.AddListener((eventData) => OnButtonSelect((BaseEventData)eventData));

        eventTrigger.triggers.Add(entry);
    }

    private void OnButtonSelect(BaseEventData eventData)
    {
        Debug.Log("Button selected!");
        // Add your custom logic here
    }
errant pecan
somber nacelle
somber nacelle
# errant pecan Kill me

that second screenshot doesn't necessarily show that you are not missing a closing brace. unless your !IDE is correctly configured, in which case you need to save your code and let unity recompile it

tawny elkBOT
errant pecan
#

Just testing you haha monkaLaugh

upper pilot
#

Not sure if that is a bad thing, but it works with that code?

#

it doesnt seem to create multiple events either, so its calling my function only 1 time even if I create that trigger multiple times.

#
        eventTrigger.triggers.Find(x => x.eventID == EventTriggerType.Select)

Perhaps I should do that?

cosmic rain
upper pilot
#

But if the event already contains all of them by default then I dont need to add it manually?
I never used this kind of code, so I am experimenting with it :d

indigo verge
#

So, I'm planning on working on a system that requires a list of prefabs in specific locations to be instantiated.

Part of that plan is a scene dedicated to "capturing" these prefabs and storing them in a Scriptable Object in edit mode. So I'd have a script that takes everything in the scene with a specific component, captures its Parent and Local Transforms, and stores them in the Scriptable Object so the collective object can be spawned from that SO.

Since Scriptable Object Runtime Edits are persistent in Editor, I should be able to simply have a normal script that edits the SO directly, and it will retain the changes due to the changes happening in editor.

Is this a good idea, or am I thinking about this from the wrong angle?

upper pilot
#
    private void AddOnSelectListener(Button button, InventoryCategories category)
    {
        EventTrigger eventTrigger = button.gameObject.GetComponent<EventTrigger>();
        if (eventTrigger == null)
        {
            eventTrigger = button.gameObject.AddComponent<EventTrigger>();
        }

        EventTrigger.Entry entry = 
            eventTrigger.triggers.Find(x => x.eventID == EventTriggerType.Select);

        entry.callback.AddListener((eventData) => RedrawInventory(category));
    }

Testing this code now

#

Yeah that doesnt work, its null

cosmic rain
upper pilot
#

yeah i agree, I should use my button script, otherwise in few weeks I will get confused by this 😄

leaden ice
#

Is there a reason not to just load the scene?

upper pilot
#

1 last test tho, I will attach event on a button EventTrigger manually to see if that works

indigo verge
upper pilot
#

        eventTrigger.triggers.Add(entry);
        eventTrigger.triggers.Add(entry);

Nevermind, its basically same as subscribing 2 times

#

Even tho you cant do that in the inspector, but it works in a script.

lean sail
indigo verge
upper pilot
#
        for(int i = 0; i < (int)InventoryCategories.Length; i++)
        {
            var instance = Instantiate(InventoryCategoryPrefab, InventoryCategoryUI.transform);
            InventoryCategoryButtonUI categoryButton = instance.GetComponent<InventoryCategoryButtonUI>();
            categoryButton.Init((InventoryCategories)i);
        }

Is there less ugly way of doing this?

#

Specifically casting enum to/from

lean sail
indigo verge
# lean sail You probably can create the prefabs at runtime, with some editor code. But why d...

You can only create prefabs in the editor, not in a packaged build. I plan on holding item cluster templates in SO assets, which I can create and edit in Editor.

For the actual built game, I'll need different methods of creating the item clusters, namely a custom item crafting system that hooks into the same parts for storing data.

I can just have the SOs hold a class which is shared with the serializable one that Players will be making/saving to JSON.

lean sail
indigo verge
#

Yeah, the usecase here is "I don't want to make an in-game item crafting system until I've tested that the underlying item systems are functional"

#

So using a scene that acts like an editor only item crafter is my plan

#

Does that make sense?

#

Plus, I can assign the editor-only SO's to enemies as template items for them to equip

fervent coyote
#

Hello-

Current I'm using Physics.Raycast for NPC's pathfinding, however they seem to get caught on objects (More specifically, objects beneath/above the raycast)

I was thinking of changing it for Physics.Boxcast (https://docs.unity3d.com/ScriptReference/Physics.BoxCast.html), but I'm worried about the performance difference between the two...
Does anyone know which is faster? Or if Boxcast is any different performance wise?

cosmic rain
#

Use the profiler to see how much impact it has on performance in your case.

#

As for your issue, might want to explain a bit better or provide a video. I don't think I understand it correctly.

dark kindle
#

why is it that if i do

if(Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.O))
        {
            Debug.Log("combination pressed");
        }

directly in Update it work but if I call a public void method containing this code in Update id doesnt work?

fervent coyote
#

Currently, I'm using dynamic pathfinding. It uses a couple Vectors for pathfinding- The NPC moves towards the target position, and if there is a wall in the wall, move to the left/right and continue until the direction you were going at is good

dusk apex
dark kindle
#

working:

  // Update is called once per frame
    void Update()
    {
        if(Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.O))
        {
            Debug.Log("SO pressed");
        }
    }
    
public void KeyCombiner()
    {
        if(Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.O))
        {
            Debug.Log("SO pressed");
        }
    }
void Update()
{
  KeyCombiner();
}

@dusk apex

#

second way

#

this the not working one

dusk apex
dark kindle
#

it just in a script that attach to canvas object and i comment out one method vs the other, i dont run both at same time

old sigil
#

Hey all I'm working on an inventory system and im running into a problem when moving the items to other slots in the inventory. when an item is picked up it seems to only want to move to other slots when you drag from the original slot it was picked up in. I was hoping someone could maybe take a little look and see if there's something logically im doing wrong, the data all sends correctly its really just the drags that seem to messed up at this point. https://hastebin.com/share/yobapapeju.csharp

cosmic rain
dark kindle
#

sure

dark kindle
#

perhaps i forgot to comment something that blocked one of method from showing

novel bough
#

Hi friends, I have a 2d grid of tiles and I can delete some tiles from the corners then I want to show a number of tiles in the text on every side and inside the cut as well, how can I do this easily?

fervent coyote
#

First, how are you doing this? Is it via scripting or gameobjects?

novel bough
#

I am generating this object grid via scripting

fervent coyote
#

Could I see what the script looks like?

novel bough
novel bough
fickle moth
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PanelMover : MonoBehaviour
{
    public float moveSpeed;
    public bool isOpen;
    public GameObject panel;
    public bool closeOnStart;
    public bool openOnStart;
    public Vector3 closedPos = Vector3.zero;
    public Vector3 openPos = Vector3.zero;
    private Coroutine moveCoroutine;

    private void Start()
    {
        if (panel != null && isOpen && closeOnStart)
        {
            ClosePanel();
            Debug.Log("Panel closed.");
        }
        else if (panel != null && !isOpen && openOnStart)
        {
            OpenPanel();
        }
    }
    [ContextMenu("Close")]
    public void ClosePanel()
    {
        if (moveCoroutine != null)
        {
            StopCoroutine(moveCoroutine);
        }
        moveCoroutine = StartCoroutine(MovePanelFromPosToPos(panel, isOpen, closedPos, moveSpeed));
        this.isOpen = false;
    }
    [ContextMenu("Open")]
    public void OpenPanel()
    {
        if (moveCoroutine != null)
        {
            StopCoroutine(moveCoroutine);
        }
        moveCoroutine = StartCoroutine(MovePanelFromPosToPos(panel, isOpen, openPos, moveSpeed));
        this.isOpen = true;
    }
    public void TogglePanel()
    {
        if (!isOpen)
        {
            OpenPanel();
        }
        else
        {
            ClosePanel();
        }
    }
    public IEnumerator MovePanelFromPosToPos(GameObject panel, bool isOpen, Vector3 to, float speed)
    {
        while (panel.transform.position != to)
        {
            panel.transform.position = Vector3.MoveTowards(panel.transform.position, to, speed * Time.deltaTime);
            yield return null;
        }
    }
}
#

free code for you guys , moves a panel from one place to another using the given speed , can tell it to open or close on start (enjoy)

#

also has context menu buttons for debugging purposes

#

you can also toggle or just open / close

fleet gorge
#

asked this across multiple servers but quick survey

somber nacelle
#

both are equally valid, there really isn't a "correct" answer here, do whichever makes the most sense for your project's style and architecture

#

although i would personally take that position, rotation, and scale and throw those into a TransformData struct and use that and the other two arguments. since that TransformData could then be reused for other things, like save data and the like

thin aurora
#

I'd argue many parameters is bad when most of them are optional

#

Then an object would suit better

#

But then again, an object is less convenient to work with

#

So yes, it really depends

fleet gorge
# somber nacelle although i would personally take that position, rotation, and scale and throw th...

theres two arguments made here

i preferred 2 because some arguments are optional, you wont always render a box with all the parameters and you might even be able to reuse the object if you call it multiple times

but low level programmers prefer 1 as if you pass in a whole object, the whole object gets put on the stack rather than some arguments being put on the register, making your code much slower esp since this is called every frame.
also, args.material is bad syntax

#

even my lecturers are split on this

#

everyone is split on this

somber nacelle
#

right, like i said both are equally valid options. choose whichever makes the most sense within the context of your project

dawn nebula
#

Anyone know the process for making your own custom LayoutGroup? The documentation is kinda.. rough.

quartz folio
dawn nebula
#

It's just it seems to require 4 method implementations, none of which are kinda clear.

dawn nebula
quartz folio
#

In your project

dawn nebula
#

Alright never mind took some fenagling