#archived-code-general

1 messages · Page 242 of 1

nova quail
#

you're right, if im trying for that approach i might aswell make many SO, but problem arises when i add enemies, multiple of them.

upper pilot
#

Maybe it doesnt work on fields?

#

I also use VS 2022 "rename" feature

#

Tested and it works fine on regular properties, but not with fields.

latent latch
# nova quail you're right, if im trying for that approach i might aswell make many SO, but pr...
public class Player : Monobehaviour
{
    PlayerSO playerSO;
    
    float healthStat;
    RegenerativeStat regenStat;
    
    //Better with init methods
    public InitPlayer(PlayerSO playerSO)
    {
      this.playerSO = playerSO;
      regenStat = new RegenerativeStat(playerSO.RegenValue);
      healthStat = playerSO.HealthStat;
    }
}

public class PlayerSO : ScriptableObject
{
    [SerializeField] float healthStat = 100;
    [SerializeField] float regenValue = 10;
    
    public float HealthStat => healthStat;
    public float RegenValue => RegenValue;
}

public class RegenerativeStat{};
upper pilot
#

Testing this:

[field: FormerlySerializedAs("<previousName>k__BackingField")]
#

Works!

quartz folio
#

🤔

#

was your field previously serialized as [field: SerializeField] public string previousName {get; set;} or something?

upper pilot
#

I tested it on a fresh one and the result was the same

#

but let me do a bit more testing, maybe I missed something

nova quail
merry stream
#

i'm tyring to understand object oriented programming. For example, i have my inventory which holds a bunch of "Items", can those items be of different item types which all derive from "Item"?

latent latch
#

No point to make a RegenPlayer : Player* class ;p

nova quail
#

I don’t think you’re getting me again. Ugh it’s so hard to explain.

vale drum
latent latch
#

Player is a mono for the reason that it exists in the scene, otherwise I'd make it a plain class

upper pilot
# quartz folio 🤔

Ok it works, as long as you specify correct variable with this attribute it seems to be doing fine.

vale drum
#

you have already the connection into scriptableobject, playerSO.HealthStat just push property there in so

nova quail
#

I think I’ll give up on this and go back to the good old script for everything, cuz this is not what I imagined at all, tought this would be much easier

#

But it’s just a mess , differently but still a mess

#

You have many tools that do everything except what I thought they did and I messed up my whole project for that

vale drum
#

unityevent event delegates and action behaviour into scriptableobjects can do a bit org

latent latch
merry stream
latent latch
merry stream
#

i have a working inventory from a tutorial but i barely understand the UI part

vale drum
latent latch
#

UI is hard because you're required to use unity tools :)

#

well, it helps shortcut a lot of stuff, but UI stuff is already another domain of stuff to learn if you've not used it

upper pilot
vale drum
#

move from class Player -to> PlayerSo :: float healthStat; RegenerativeStat regenStat;

latent latch
#

oh wait im dumb you're right

upper pilot
#

yep I was worried for a second that this is correct, after all I've been through with SOs lol

latent latch
#

im reading comments above thinking I missed something, but I added on dot operators

vale drum
#

Yes Player is MonoBehaviour because you use it as component in gameobject, but other 2 variables.

merry stream
latent latch
#

I suggest youtube videos for that

vale drum
#

coud be also a course or video c#

upper pilot
# merry stream i have a working inventory from a tutorial but i barely understand the UI part

Thats why I said earlier, dont follow tutorials like that.
Unless they explain everything and you understand everything they do.
You will be able to somehow do 1 part but have issue with another.

The best way to learn is to do your own thing and learn how to use the tools, instead of learning how to make a game system.
Example: you want to make Inventory system.
You need to know how to use a List, enums(probably) then watch a tutorial on how to use List and enums and use what you learn to create Inventory system.

#

Ofc asking for help on what approach is best is a good idea as you cant figure out everything on your own easily.

merry stream
#

and not because of the logic, just the unity stuff

upper pilot
#

So what is the issue with UI?

vale drum
#

Entitiy woud be a cool stuff if it would easy exist, where a gameobject is lite and dont have roation iin every level of gameojbect hierarchy, and size vector4, to be real i would prefer just having one more bool isPosition=false;

pulsar holly
merry stream
#

nothing, it works but I need to change it so you can't drag certain item types on certain slots, ie. weapon into boots slot

#

not entirely sure how to

upper pilot
#

Which tutorial are you following?

merry stream
#

dapper dino

vale drum
#

monkey code

upper pilot
#

aaaa probably the one I used to watch in the past.
basically you need to find a function that has "onItemDropped" or something and do a check here.
Either way, I remember those tutorials and it was hard to add any new behaviour unless you understand the code 100%

#

You said the issue is with UI tho

merry stream
#

wait maybe i'm thinking about it wrong

upper pilot
#

Basically prevent item from being dropped on a slot.

merry stream
#

its hard to seperate the UI and logic in my mind, should I just implement the checks within the ivnentory logic and the UI will figure itself out?

upper pilot
#

well idk, I always try to separate UI and logic and only use Events.

merry stream
#

yeah I did

upper pilot
#

What I do is make sure that UI only reads the data from your scripts thats it.
So your UI might have a box where you drop an item, that box should have an listener/event that is fired when you drop an item on it.

#

Then your logic will handle what happens to the item(i.e. is it equipped or does it go back to the inventory)
Then UI should update.(or at least relevant pieces of UI)

#

I use Events for those pieces so I can update w/e I want when an item is moved/removed etc.

merry stream
#

so don't parent and set trasnform within the UI code?

upper pilot
#

But for simplicity you can just redraw whole UI on demand 😄

#

This is fine I think?
It's not logic related to your data, but logic related to UI stuff i.e moving an image with a mouse right?(that image holds data probably and when you drop it on a box that data is sent with an event)

merry stream
#

ok ok so just make it so in the ui if I drop it on a certain slot it wont send the event to the inventory?

upper pilot
#

I dont think UI should "assume" that an item was equipped successfully

#

depends on how its implemented, but UI doesnt know if you were able to equip the item.
Ofc if your game is simple and the only requirement to equip an item is item type...
Then item can have enum for type + ui box(equip slot) can also have enum.

#

Regardless your logic needs to know that you equipped an item.

merry stream
#

alright, makes sense

#

what youtubers do you recommend to watch to learn these things?

latent latch
#

if you're using drag features like mouse or finger then youll want to look into IPointerHandler and IDrag interfaces

merry stream
#

yeah i'm using those

vale drum
#

have you try the sample there PaddleBallSO,
if yes how is it that slow using Loose coupling, high cohesion. threads/wait mainthread is my guess?

upper pilot
#

if u just want to watch then code monkey is good probably.

#

Like I said before, I cant recommend learning how to code from tutorials.
From my years of experience "learning" it just never works.

Unless it works for you somehow.
Are you able to recreate this inventory system from scratch without watching a tutorial?

#

Or do you need to double check how things work and why?

#

I can recommend watching tutorials, but dont "follow along", but instead use what you learned and apply it to your own systems.

latent latch
#

id skip the design and just get it functionally working

vale drum
#

if you had decades of xp in code / c# than you wonder how dirty code is faster than clean fail in its organisation overhead

#

almost no one talks on hype of dots / entity / webgl-support their treads reduced in one / architecture priority by cores

vale drum
#

c# is mutch faster but the implementation in current version is old, await c# 9 close closer to c++ boost
and everything have to be rewritten one day if ansi/iso c# for gpu(logic in shaders) not closedSource nvidia but av1

upper pilot
#

How to force Unity/VS2022 to recompile the code?
After some changes and moving files my scripts are greyed out on game objects and I cant do anything to fix them.
I cant fix an error, because fields are not serialized so they are null.

vale drum
#

ALT + TAB

upper pilot
#

That doesnt solve the issue.

#
The referenced script (Unknown) on this Behaviour is missing!
#

But the script is there and when I click on it, it shows the location of the script.

swift falcon
vale drum
#

if you switch the application into a unknown example calc, it schould detect , than ALT+TAB again and recompiled auto

upper pilot
#

I had to manually assign those and the game worked fine, but after I closed Unity it broke again, but thiss time script is visible in the inspector, but its not serialized so I cant fix it.

upper pilot
gray fiber
#

Someone please help me I have been stuck on this for hours:

This script is for catching fish in my 3D fishing game. It all works except for one thing: it won't catch more than one fish at a time. What I am trying to do is with the for loop iterate through however many times my maxCatchCount says to. I made it this way because I'm making it so the player can buy an upgrade to catch more fish at a time, and each time the upgrade is bought it increases maxCatchCount by 1. For some reason no matter what I put maxCatchCount at it will only catch one fish at a time. (btw when it "catches" a fish it just instantiates an object version of that fish and throws it at the player)

variable meanings:

maxFishCount - amount of fish the player can catch with one reel
bitingFish - a collider that keeps track of all the fish under the bobber than can be caught
FishType - the type of fish being caught (there are 3 different fish), keeps track of what to give to player

upper pilot
#

When I manually drag a script:

Can't add script component 'AreaInfoUI' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.
vale drum
upper pilot
#

There are no compile errors tho(not until I start the game)

swift falcon
upper pilot
#

Yes

#

So this issue happened when I moved scripts around to organize and after I restarted Unity.

vale drum
#

rename back and copy the code, into a new renamed class

#

than copy values from one to other, prefab/so

upper pilot
#

Its not just 1 script tho

#

Is there a better way?

vale drum
#

if you rename you loose values of inspector

upper pilot
#

its fine

#

I can reassign those

swift falcon
rain minnow
upper pilot
#

I guess that was a mistake

rain minnow
#

Use Unity to move your files and create folders; it brings the meta files with it . . .

swift falcon
upper pilot
#

Can I restore meta files

#

or recreate them

swift falcon
#

sounds like its time to consider a version control system XD

upper pilot
#

Either way there are no meta files in Assets folder, everything was moved

swift falcon
upper pilot
#

I do have it, but I dont want to restore all of the changes lol

west sparrow
gray fiber
upper pilot
#

is there really no magic button to remove meta files and recreate them, I dont mind assigning scripts manually to each game object 😄

west sparrow
swift falcon
rain minnow
upper pilot
gray fiber
swift falcon
upper pilot
#

It didnt rename it

#

Do you mean to delete Library folder?

#

ok so it actually renamed the file

#

It just doesnt show it in VS

swift falcon
upper pilot
#

guess I needed to alt tab, either way renaming file in VS renamed it in the Unity.

vale drum
#

in code editor of vs 2022 s/he means to press F2 to rename a method/class (class rename changes files correctly)

upper pilot
#

It just needed to compile it

#

Yes ctrl + R

rain minnow
#

You have to let Unity finish recompiling for it to update . . .

upper pilot
#

or right click a class name

vale drum
#

auto-save-scenes on play in settings is also a incl. feature, Preferences -> Generals

upper pilot
#

so do be clear, do I remove Library folder?

upper pilot
#

Renaming class didnt fix the issue

swift falcon
#

worth a try I'd say....

#

sometimes simply restating Unity does miracles!!! (don't tell anyone!)

vale drum
upper pilot
#

I tried that, in my case Restarting Unity caused this issue to happen

#

It worked fine before I restarted :x

swift falcon
#

that's a... miracle, too!

vale drum
#

restart all devices even cars of today, take battery out and reboot, than update fixes all (bugs)

upper pilot
#

I wish Unity was smarter

swift falcon
#

Soon™️

vale drum
#

actually if i see so many packages and versions its a miricale how they go fine in c# (not like pyhthon jova breaks)

spring creek
#

Did you delete the library?

upper pilot
#

Yeah its doing Unity things now, loading a project

swift falcon
upper pilot
#

Going to take a while

rain minnow
upper pilot
#

oh like that

vale drum
upper pilot
#

I think removing library might be a fix, I just need to reassign things in inspector

upper pilot
vale drum
#

have you give your project to other gamedev, so check the unity version ( downgraded 2019 ? )

swift falcon
#

@upper pilot to answer your original question (although that's probably not what you need rn), it's this little guy: EditorCompilation.CompileScripts (it's internal dow!)

upper pilot
#

its weird that even after removing Library, it didnt remove all from inspector, only broken scripts I think.

swift falcon
#

what a doubling down situation...

upper pilot
subtle niche
#

can anyone help me I have this script were im trying to spawn objects on terrain based on texture
but i get an index out of bounds error when i hit play and nothing spawns

upper pilot
swift falcon
vale drum
upper pilot
#

alright, Removing Library is a solution that I will keep in my heart just like restarting PC helps, even tho I had to do some work, but it only required me to fix inspector issues for previously broken scripts.
All prefabs and most of my game objects were intact.

upper pilot
#

We are on the latest 2022, so there isnt much we can update to.

upper pilot
#

I dont think I ever tried to downgrade tho, but I'd rather not risk more issues lol

vale drum
#

deprecated

swift falcon
#

make a copy of the script content, and paste in a newly created script maybe?

what next? install a v8 engine?

upper pilot
#

Yeah copying the script was my last resort really

vale drum
upper pilot
#

As I would have to redo quite a bit of them

swift falcon
vale drum
#

save your 50 cents, woud have been a arcade machine world of games

vale drum
tawny elkBOT
vale drum
untold shard
#

Guys it's possible to get a collision trigger pos between 2 gameObjects? Not relative to any of the gameObjects because one of them is deleted after the collision and if it's applied to the other object the sound will not be in a good position (collision trigger,not solid)

vagrant blade
#

What does that even mean?

untold shard
#

I want, as I said: to detect the collision position between 2 triggers (without referring to the position of any of the 2 objects but only where the collision occurs) xd

vagrant blade
#

If that's what you said, that's what you would have written instead of whatever that previous splurge of words was

#

Nevermind, you're using triggers. Trigger collision doensn't give you contact points.

spring creek
#

I was gonna suggest raycasting, but I see that is the top answer there. So I just second that

untold shard
#

ok thanka

merry stream
#

can I use scriptable objects to achieve the same thing as singletons? for example i have this scriptable object which is an inventory that holds 70 slots

dusk apex
#

The normal use-case would be having non mutable data that are independent of the Game Object

merry stream
#

is it bad to use it in this way?

#

aren't singletons supposed to be immutable too?

dusk apex
#

ie References between scenes of mutated SOs will likely be referring to different instances.

merry stream
#

well i'm not changing anything during runtime

dusk apex
#

Your VoidEvent might suggest otherwise but alright.

merry stream
#

im changing the ItemContainer but not the inventory itself no?

dusk apex
#

If you're simply going to be referencing something not related to any scene, it should be fine.

merry stream
#

what do you mean?

dusk apex
#

I don't know anything about your program, so just tryitandsee ..

drifting crest
#

Hey guys I have one main Game scene in which there are 3 buttons and on clicking on of them it loads the respective scene of it , but when I click and it loads that particular it destroys the UI of that scene i tried using DontDestroyOnLoad on the canvas but no shot

fervent furnace
#

is the gameobject moved to ddol scene after you enter play mode?

drifting crest
fervent furnace
#

have you checked the console?

drifting crest
fervent furnace
#

is the canvas root object?

#

btw not debug.log but to read any messages/warnings/errors

deft kindle
#

Hi i have a weird question i dont Seem to find anything about This but i want to find out where the player presses on the screen in a area so i Can fire a projectile its a 3D game

fervent furnace
#

raycast to see if the screen ray hits the "area" (collider)

thick iron
#

how do i have a limit for scroll view?

#

like a limit of scrolling

worthy crane
#

can someone help me with gitignore?

I have this folder structure.
I want to ignore everything in journeymap/
but unignore everything in waypoints/

I tried this patterns but it still doesn't work

1 attempt

!journeymap/**/**/**/waypoints/*
journeymap/*

2 attempt

!journeymap/**/waypoints/*
journeymap/*

3 attempt

journeymap/*
!journeymap/**/waypoints/*
somber tapir
worthy crane
#

Like now in git remote repo I have "Дім" and "Гравій". But other things are ignored in git status --ignored

heady iris
#

So the problem is that things are being ignored that shouldn't be

#

this is neither unity nor code related, by the way..

worthy crane
#

But all programmers are using git, so I thought to ask here

buoyant crane
tropic kiln
#

Heya, I'm doing some procedural world generation and I'm working on biome blending at the moment.

In short I generate cell value noise to define which biome should go where (https://gyazo.com/32b32c583f21924502f1695e5e006ad0) and then use the Distance 2 Div return function on the same noise to adjust the blend (https://gyazo.com/f68e3ec690a94976525425e9c370fee5).

Only problem is, when I have two of the same biome adjacent to eachother, it still blends and just looks like trash tbh (It's clear to see here - https://gyazo.com/c67aed1c384cc966a41a160bbc4e7e4c). Any ideas how I can detect when this happens and choose to exclude the blend calculation on that edge?

hallow portal
#

does some1 know a salution my player is a prefab and i have: public GameObject inventoryObject; where i need to put a ui on but i cant if i do i get a type mismatch does any1 know a salution?

rigid island
zinc thicket
shrewd roost
#

I am making a card game. The general concensus seems to be a good way to save card data is in scriptable objects. My problem though is how to access that data at runtime. If I need to get a card's name, how am I supposed to load it from the assets? The logical way would be using the resources folder, but people say that best practice is to not use the resource folder at all, so I don't know how people tend to approach this

somber tapir
shrewd roost
rigid island
#

what inefficient dragging a bunch of assets in a slot ?

hexed pecan
#

Nothing wrong with loading them automatically from Resources in this case IMO

somber tapir
shrewd roost
hexed pecan
#

Can also just load a single SO that just holds references to the card SO's

shrewd roost
hexed pecan
#

Probably the same memory wise

turbid surge
#

Does anyone use a SQL database for their unity projects? Is there an entity framework similar package out there?

#

I want to try using SQL lite for a local DB but couldn't store certain things without a complex mapping process

fluid wedge
#

Hey guys! I'm changing engines to Unity, and I've understood how things work.

I need some insight into how code is to be structured in such an OOP based engine.

Suppose I have a gameLoop script which instantiates car objects, which have a Drive script under each of them, and destroys them when they aren't required.

How can I send events to these cars that the game has ended, so they must stop running their movement code, and start decelerating till they are deleted by the gameLoop script?

somber tapir
fluid wedge
#

or do you mean enabling the script at start of game?

#

that would make more sense

turbid surge
# knotty sun what are you trying to store?

game assets. I used to create scriptable object 'databases' that contained scriptableobjects of resources I needed. But i been out of Unity for a long time and I dont want to handle retrieving stuff with a weird singleton/ list of Scriptable objects pattern I used to do.

somber tapir
turbid surge
#

i was hoping I could do something ASPNET style and use zenject to inject a dbRepo service and get my info that way

rigid island
#

can't you just host the asset bundles ?

#

use CDN

#

how much data you need, Unity has storage for assets

#

they give you Free 50GB(bandwidth) i think

#

only 5GB data tho

turbid surge
#

I was hoping for just a local sqllite or something I wanted to make a little singleplayer game while im on vacation I think CDN is overkill

#

I suppose I want to know if theres something like zenject which gives me familiar functionality for dependency injection

#

but instead of DI I want a familiar functionality for a DB service repo pattern to that of an API or something

marsh socket
#

hey guys what do i do if im having an issue with a game which is runned on unity?

sleek bough
marsh socket
sleek bough
#

Then you're out of luck

marsh socket
rigid island
#

can't you just use a DLL/ external Library?

rough sorrel
#

Hi. Is there a way to have an image be in the UI but where the real world object is please? Like, I have a position in the real world, and I want to display an image where that position is but in the 2D canvas. If it was a screen space canvas I could use the WorldToScreenPoint, but as if it a world canvas, that doesn't seem to be working. I don't know if I'm explaining myself.

cold parrot
# turbid surge but instead of DI I want a familiar functionality for a DB service repo pattern ...

In many cases ORM doesn’t make much conceptual sense in games since we typically don’t want to persist all data changes immediately or even use OOP patterns heavily. Therefore abstracting persistence (or making it transparent isn’t immediately helpful). What you’d typically do is write to a game state datastructure in memory and just make sure that everything can restore from having just that data. Then simply snapshot that to a file on demand. Also considering the dynamic nature of gamedev relational structure quickly gets in the way so you often end up with a key-value store with some homebrew implementation of object references. Only if you truly need joins and transactions would a RDB make sense. Obviously migrations and such are more annoying with a schemaless database. It’s a compromise whichever way you go.

#

The best ORM you’ll get in a game is using an ECS which is essentially already a RDB and you’ll have a game that fundamentally treats everything as a CRUD operation —> no need for mapping because: no OOP

somber tapir
rough sorrel
#

didn't work, already tried 😦

somber tapir
rough sorrel
#

but that would make the uiElement be like in z=-100000, so it wouldn't be visible

somber tapir
rough sorrel
#

with that it only does like a shadow

somber tapir
tacit swan
#

im making a behavior tree and one of my nodes is for pathfinding. However, my pathfinding code is in a different script called "Unit" which starts a coroutine to initiate pathfinding. How can i start this coroutine from my node class? I can't call coroutines from the node class since it doesn't inherit from monobehavior

leaden ice
#

You could have a script/MonoBehaviour in the scene whose sole responsibility is to run coroutines for your nodes

tacit swan
#

tyty

tacit swan
spring creek
heady iris
#

You just need to nail down how information goes between those two worlds

#

I've done a gameobject based player and tons of entities based enemies, for example

tropic kiln
#

Anyone know why when setting certain textures on my material it maps weird? The properties tab on the left is that of all chunks, the one on the right is what it's supposed to be. I'm literally just referencing a pixel from those textures but it's being distorted in some way and I'm not sure why...

https://gyazo.com/571808f9e8ea738c41e44b9f9f97d6d6

#

It could be that I'm getting the pixel billinearly?

#

Then again I'm doing that with each texture so it should be relative

dry crest
#

Hi all, if I'm in the wrong spot please let me know. I have been working on upgrading from 2022.1.23f to 2022.3.15 and have a persistent issue I can't seem to find a resolution to. I've done a lot of searching (including in this discord) but either my issue is incredibly unique, or so simple that I'm just not seeing the obvious. Can anyone help? The issue appears to be an exception finding api-ms-wind.core-heap-l1-1-0.dll. The head scratcher is that the DLL is there, and I've been through many steps to confirm the existence on my system (including a number of reinstalls of C++). It also seems this assembly is used for compiling IL2CPP, but I'm using Mono for my scripting backend.

Anyway, if there's somewhere else I should be asking please let me know. Thanks for your help!

  at (wrapper managed-to-native) Interop+mincore.GetProcessHeap()
  at Interop.MemAlloc (System.UIntPtr sizeInBytes) [0x00000] in <7ec8e29954a6455daa48484a381ec418>:0 
  at System.Threading.Win32ThreadPoolNativeOverlapped.AllocateNew () [0x00053] in <7ec8e29954a6455daa48484a381ec418>:0 
  at System.Threading.Win32ThreadPoolNativeOverlapped.Allocate (System.Threading.IOCompletionCallback callback, System.Object state, System.Object pinData, System.Threading.PreAllocatedOverlapped preAllocated) [0x00000] in <7ec8e29954a6455daa48484a381ec418>:0 
  at System.Threading.ThreadPoolBoundHandle.AllocateNativeOverlapped (System.Threading.IOCompletionCallback callback, System.Object state, System.Object pinData) [0x00044] in <7ec8e29954a6455daa48484a381ec418>:0 
  at System.IO.Pipes.PipeCompletionSource`1[TResult]..ctor (System.Threading.ThreadPoolBoundHandle handle, System.ReadOnlyMemory`1[T] bufferToPin) [0x00023] in <60e86e30be2149bea172ff3128793984>:0 
  at System.IO.Pipes.ConnectionCompletionSource..ctor (System.IO.Pipes.NamedPipeServerStream server) [0x0000c] in <60e86e30be2149bea172ff3128793984>:0 
  at System.IO.Pipes.NamedPipeServerStream.WaitForConnectionCoreAsync (System.Threading.CancellationToken cancellationToken) [0x00019] in <60e86e30be2149bea172ff3128793984>:0 
  at System.IO.Pipes.NamedPipeServerStream.WaitForConnectionAsync (System.Threading.CancellationToken cancellationToken) [0x0004a] in <60e86e30be2149bea172ff3128793984>:0 
  at (wrapper remoting-invoke-with-check) System.IO.Pipes.NamedPipeServerStream.WaitForConnectionAsync(System.Threading.CancellationToken)
  at IPCConnection+WrappedNamedServerStream.WaitForConnectionAsync (System.Threading.CancellationToken cancellationToken) [0x00000] in <3f5bd82a14d442d9848a73363c91f22e>:0 
  at Bee.BeeDriver.BeeDriver_RunBackend.RunBackend (Bee.BeeDriver.InternalState state, NiceIO.NPath newDagJsonFile, System.Action`1[T] nodeFinishedCallback, Bee.Core.Track mainAsyncTrack) [0x00182] in <3f5bd82a14d442d9848a73363c91f22e>:0 
  at Bee.BeeDriver.BeeDriver.EntryPoint (Bee.BeeDriver.InternalState state) [0x00161] in <3f5bd82a14d442d9848a73363c91f22e>:0 
  at Bee.BeeDriver.BeeDriver+<>c__DisplayClass0_0.<BuildAsync>b__1 () [0x00074] in <3f5bd82a14d442d9848a73363c91f22e>:0 
  at Bee.BeeDriver.BeeDriver.AwaitAndCatchExceptions (System.Func`1[TResult] action) [0x00070] in <3f5bd82a14d442d9848a73363c91f22e>:0 ```
zenith bane
#

Hello, I created a Scriptable object, and it was Debug.Log in "OnEnable" method. When I run game in Unity IDE, I see the message in the log, but when I publish game on Browser/WebGL it does not log it (and other functions are not working). I did it for Input management. Am I missing something here?

dry crest
#

Did you build in developer mode?

#

Actually, I'm not conversant with whether that is required for WebGL, but I do know that Debug.Logs don't show in local bulids unless it's built in developer mode

zenith bane
#

So, while I am not sure this is the case
https://stackoverflow.com/questions/40208352/onenable-function-from-of-scriptableobject-not-being-called
But in this SO thread, they say, Scriptable objects are not included in the Scene automatically in builds. So I need to initialize them at once. So it is a misleading behavior in Unity UI, that included automatically on play button press.

#

I will create a Singleton or similar at game start and initialize it. Let me see if that works.

dry crest
#

True, if the object it not actually used in the scene then it may not be included in your build

somber sparrow
#

void OnTriggerEnter2D(Collider2D other)
{
GameObject otherOBJ = other.transform.parent.gameObject;

    Debug.Log(other.transform.tag);
    switch(other.transform.tag)
    {
        case "Weapon":
        health -= otherOBJ.GetComponent<sword2Parent>().damage;
        break;

        case "Projectile":
        Debug.Log("hit projectile");
        health -= GameObject.Find("soccer ball").GetComponent<basicSoccerBall>().damage;
        Destroy(other.gameObject);
        break;

        case "Explosion":
        Destroy(other.gameObject);
        break;
    }

}

#

Please help this only works for the weapon ive been trying to figure out why its not working for days, i need to fix it because this is a christmas gift for my friend.

#

Whenever another one hits the console gives this error code: NullReferenceException: Object reference not set to an instance of an object.

heady iris
#

well, what line is it on?

heady iris
#

you need to know where the error's coming from if you're going to fix it

somber sparrow
#

says its on the GameObject otherOBJ = other.transform.parent.gameObject; line

rigid island
heady iris
#

sounds like that object doesn't have a parent, then

somber sparrow
#

wait i think i get it; before the code can carry on it has to find that object which is only needed for the weapon

#

thank you so much i think i understand

rigid island
#

if there is no parent, its null

somber sparrow
#

yes because the weapon object i was finding through that line has a parent that has the script

rigid island
#

you should probably clean these up with some Components

heady iris
#

yes: references stored in variables you assign in the inspector

somber sparrow
#

the sword is the collider and to make the sword slash i had the parent as a rotating empty object

#

ik what components are thx

heady iris
#

instead of just searching for components and hoping they're in the right spot

heady iris
#

you do have "sword2Parent" and "basicSoccerBall" at least

rigid island
#

if(other.TryGetComponent(out sword2Parent sword))
sword.damage

heady iris
#

i am being assaulted by a cat and cannot help further

#

aaa

rigid island
#

oh wait wth is this
GameObject.Find("soccer ball").GetComponent<basicSoccerBall>().damage;

somber sparrow
#

IT WORKS THANK YOU

#

void OnTriggerEnter2D(Collider2D other)
{

    Debug.Log(other.transform.tag);
    switch(other.transform.tag)
    {
        case "Weapon":
        health -= other.transform.parent.GetComponent<sword2Parent>().damage;
        break;

        case "Projectile":
        Debug.Log("hit projectile");
        health -= other.transform.GetComponent<basicSoccerBall>().damage;
        Destroy(other.gameObject);
        break;

        case "Explosion":
        Destroy(other.gameObject);
        break;
    }

}

rigid island
#

oh ok

#

kinda made it slightly less worse

#

you dont need the switch for the first two

somber sparrow
#

i cant use a component for this script because i cant declare other outside of the ontriggerenter, so i just created a gameobject in that void

somber sparrow
rigid island
#

so the tag is kinda pointless no?

somber sparrow
#

but then id have to run through a line for each script name

#

like
other.getcomponent soccer ball.damage
other.getcomponent sword.damage

that would cause the issue i just experienced right

rigid island
# somber sparrow but then id have to run through a line for each script name
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.transform.CompareTag("Explosion"))
        {
            //stuff
            Destroy(other.gameObject);
            return;
        }
        if(other.TryGetComponent(out sword2Parent sword))
        {
            healthBar -= sword.damage;
        }else if (other.TryGetComponent(out basicSoccerBall soccerBall))
        {
            healthBar -= soccerBall.damage;
        }
    }```
#

sword2Parent is a shitty name for a class

#

c# classes should also be PascalCase

#

meaning capitlize every word

somber sparrow
#

interesting... im just gonna stick with what i have for now though because i need to get this game done before christmas

rigid island
#

alr. any further question though should go in #💻┃code-beginner
this channel assumes you know this stuff

delicate olive
reef escarp
#

Hi all. How can I make it so that the player can Pick up an item so that he holds it in his hands not in the inventory, and so that I can do it through another script to do Put the item in the place I want (It is desirable that the item after I put it in the place indicated so that it immediately teleported to the specified coordinates). I will be very glad for any help 😄
Thank you in advance

delicate olive
reef escarp
rigid island
delicate olive
# reef escarp Hi all. How can I make it so that the player can Pick up an item so that he hold...

But you could do something like this maybe:

  1. Shoot a raycast from the player's camera straight forwards and if it hits an object that's hittable, continue to the next step
  2. Display some ui and prompt the user to press "E" for example to pick the item up
  3. When "E" is pressed, disable rigidbodies for example and teleport the object to the hand
  4. Now that the player's hand is occupied, block any further raycasts until the player presses "E" again and when they do so, raycast again and teleport the object to that raycast's hit destination and unoccupy the hand
reef escarp
#

Is it possible to send messages in this section #1062393052863414313 so that I can describe everything in my problems in detail?

delicate olive
reef escarp
quartz folio
#

I have deleted your post. That section is for DOTS.

#

Hence its name and pinned post.

reef escarp
quartz folio
waxen jasper
#

I'm getting "Failed to find entry-points:
System.Exception: Unexpected exception while collecting types in assembly `Unity.PlasticSCM.Editor, " after removing plasticscm than reinstalling it. I created a repo under the wrong organization the first time so i had to delete it. plasticscm seems to be working fine the error is just annoying and probably has to do with a remnant from the first install. The error pops back up whenever i stop the player.

tacit swan
#

when i try to inherit from ComponentSystem it says that the namespace isn't found

#

any help would be greatly appreciated

stable marsh
#

After I've shot, I want my vertical recoil to return to the original rotation unless I've moved the mouse down. The problem right now is it doesn't go back down far enough. Am I calculating the amount to return by correctly? Am I applying it correctly?

    public void GenerateRecoil()
    {
        recoilTime = gunData.recoilDuration; // reset durations
        recoilRecoverTime = gunData.recoilRecoverDuration;
        recoilReturnTime = gunData.recoilDuration;

    }
    private void LateUpdate(){
        if (recoilTime > 0){ 
            povComponent.m_VerticalAxis.Value -= (gunData.recoilX * Time.deltaTime) / gunData.recoilDuration; // move the camera vertical axis by recoil amount
            recoilReturn += (gunData.recoilX * Time.deltaTime) / gunData.recoilDuration; // add the same amount to a variable

            recoilReturnAmount = recoilReturn + povComponent.m_VerticalAxis.Value; // calculate where to return to by adding the current vertical rotation to the amount changed
            recoilTime -= Time.deltaTime;
        }
        else if (recoilRecoverTime > 0 && isShooting == false){
            povComponent.m_VerticalAxis.Value = Mathf.SmoothDamp(povComponent.m_VerticalAxis.Value, recoilReturnAmount, ref recoilReturnVelocity, gunData.recoilRecoverDuration); // move the cameras vertical axis to the calculated return angle
            recoilRecoverTime -= Time.deltaTime;
        }
        else if (recoilReturnTime > 0 && isShooting == false){
            recoilReturn -= (gunData.recoilX * Time.deltaTime) / gunData.recoilDuration; // reset the recoil return over time
            recoilReturnTime -= Time.deltaTime;
        }
        

        if (povComponent.m_VerticalAxis.m_InputAxisValue < 0) // if you move the mouse down
        {
            recoilReturn = 0; //reset the amount to return by
        }
    }
chrome trail
#

So exactly how do animation events work for animation states that try to blend two animations together? Does it just play the events from both of them?

swift falcon
#

also, I have a console log that tends to get spammed just to update a value...

would be possible to reuse that log instead of printing another, with the new value?

thin hollow
#

Is there a way with Physics.BoxCast to calculate where would be the center of the box I'm projecting relative to the returned hit coordinate? I don't think RaycastHit has that property...
With sphere cast obtaining center is easy - you just subtract normalized direction of the cast multiplied by the sphere's radius, but with box I'm not sure I understand how to proceed.

quartz folio
#

Same logic for any cast

chrome trail
#

So the normalized transition time in Animator.CrossFade, does it go by the normalized time of the current animator state or the normalized time of the state the animator is trying to transition to?

heady iris
#

In the case of a swept volume or sphere cast, the distance represents the magnitude of the vector from the origin point to the translated point at which the volume contacts the other collider.

this is a bit hard to parse

#

i guess that does mean it's the distance to the center of the box upon impact

quartz folio
#

Don't have to guess, I wrote a debugging library that uses the logic

heady iris
#

good to know!

rigid island
#

try to make values OnGui instead of console because i prefer looking at my values at runtime in fullscreen (for debugging)

#

or maybe unity UI

#

if you need those constant update method values ya kno

swift falcon
swift falcon
#

a regex based collapse implementation would be cool 🤤

west lotus
calm talon
#

I have some code that loads the scene the game takes place within from the title screen, and it works fine initially, however when returning to the title screen from the game, nothing after the first yield return runs

    public IEnumerator Load(string txt)
    {
        yield return new WaitForSeconds(txt.Length * titleText.writeDelay);
        SceneManager.LoadScene(1);
        yield return new WaitForSeconds(0.1f);
        controller = GameObject.FindGameObjectWithTag("Player").GetComponent<Player_controller>();
        controller.LoadGame();
        Destroy(transform.parent.gameObject);
    }
rigid island
calm talon
#

no

rigid island
#

did you check console for errors

calm talon
#

the gameObject is only destroyed at that last line in the coroutine

calm talon
rigid island
#

well you're switching the scene no? I dont think the rest would execute..

calm talon
#

(the gameobject is not destroyed on load)

rigid island
#

object get destroyed when you switch scenes

#

oh ok

calm talon
#

as I mentioned earlier, the code works like a charm initially

rigid island
#

and you are starting coroutine within this clasS?

calm talon
#

yes

#

The bug ONLY occurs upon returning to the title scene

#

not when starting in the title screen

#

and using print statements to follow execution demonstrates that nothing post the first yield statement runs

rigid island
#

yes i know but if its started from another object the coroutine technically ran on other object and if thats destroyed on scene switch it could be possible

rigid island
#

alr need to provide a bit more context

#

just guess work rn because can't see the full picture

calm talon
#

here's the hierarchy rq

#

class is attached to the ButtonController GameObject

rigid island
#

which one is DDOL btw

calm talon
#

Title Screen

#

(the parent of ButtonController)

#
    public void LoadGame()
    {
        for (int i = 0; i < buttons.Length; i++) buttons[i].interactable = false;
        string txt = "fetch Memory";
        titleText.WriteStart(txt);
        StartCoroutine(Load(txt));
    }

this is the code that calls the coroutine btw

#

all of the above runs nominally in any scenario

swift falcon
calm talon
#

that's a thing?

rigid island
#

no

swift falcon
#

sorry

#

I meant

#
yield return SceneManager.LoadSceneAsync(1);
calm talon
#

I just didn't know that's a thing

rigid island
#

I mean yeah loading isn't the problem though right? its loading back in?

#

can you show that, also did you debug txt.Length * titleText.writeDelay's value ?

swift falcon
calm talon
#

was one of the first things I did lol

rigid island
#

do you mess with TimeScale anywhere ? would be good to know what you tried to debug this

calm talon
#

I don't change timescale whatsoever within the scope of this

swift falcon
rigid island
#

not just this script

calm talon
#

It does change, but it's not relevant to this

#

*it only changes inside the actual game's scene, not the title scene

#

the game's scene is never loaded in

rigid island
#

oh ok , jus checking because that would stop it

calm talon
#

and as I've mentioned prior, it works fine initially

rigid island
#

well with little knowledge i have I could assume timescale changed somewhere else and never put back? idk your setup lol

#

just trying to rule out the common coroutine issues

calm talon
#

that may be it

#

must be a 2022 thing since I never had an issue with that in the 2019 version

rigid island
#

that basecode would't change between 19 and 22

calm talon
#

time.TimeScale = 0 when the game is paused

#

and the player goes to the menu when the game is paused

rigid island
#

timescale is a global setting so it wont reset if you changed it in another scene

calm talon
#

and it never undoes that timescale change

#

I never had an issue with that in Unity 2019

rigid island
#

i doubt they changed how it function but Ig anything is possible with unity.

calm talon
#

IT WORKS

#

thanks for the help mate

rigid island
#

no prob glad it worked out 🙂

fluid wedge
#

Hey guys! I'm getting an expected error and I found nothing helpful on searching for it.

I have a Stadium gameObject (empty) with a Stadium script. I store a list of GameObjects in that script.

When I run the game, it shows me the following error

#
public class Stadium : MonoBehaviour
{
    public Rigidbody2D ballBody;
    public Transform[] Rows;

    Transform activeRow()
    {
        Transform closestRow = Rows[0];
        float closestDist = Mathf.Infinity;

        foreach (Transform row in Rows)
        {
            float dist = Vector3.Distance(row.position, ballBody.position);
            if (dist < closestDist)
            {
                closestRow = row;
                closestDist = dist;
            }
        }

        return closestRow;
    }

    void Update()
    {
        Transform activeRowNow = activeRow();
        Debug.Log(activeRowNow.gameObject.name);
    }
}
#

code errors at Transform closestRow = Rows[0]

fervent furnace
#

change it to serializefield private first

swift falcon
fervent furnace
#

declare everything as public not a good idea and other scripts can change this field (probably the causes of missing reference)

fluid wedge
#

there is only one script in the whole project, the one I sent above

swift falcon
fervent furnace
#

probably duplicate script
insert a single debug.log (Log("called") or whatever you like) or search the component in hierarchy

lean sail
fluid wedge
fluid wedge
#

if it helps, even during runtime, the field values are not null in the inspector, they still show the intended gameObject values.

rigid island
fluid wedge
rigid island
#

what is entire stacktrace

fluid wedge
#

this points to the Vector3.Distance() line btw

rigid island
#

the script + object

rigid island
fluid wedge
rigid island
#

thats assigning

#

the reference

fluid wedge
#

but it would give null if it didnt exist (if im not wrong)

fervent furnace
#

i will debug.log everything, some elements are null but it seems impossible

rigid island
#

which is why something is wrong , the list isn't null

fervent furnace
#

the array is not null btw

lean sail
fervent furnace
#

i see the inspector shows the array is filled

rigid island
#

worth a try to just recreate this object and attach script again 🤷‍♂️

fluid wedge
#

I know that this isn't a loading problem, because Debug Logging on update keeps printing the same error

rigid island
#

no code related

#

use scriptable object tiles or prefab tiles

icy herald
#

sorry

fluid wedge
#

Uh guys I just created the StadiumObject again, attached script and put the values in and it worked

icy herald
fluid wedge
#

anyone know why this happened in the first place though?

rigid island
fervent furnace
#

there are scripts create that based on composite collider 2d, you can google it

rigid island
fluid wedge
#

ok

rigid island
#

its pretty uncommon tho tbh

#

when you attach script to object it creates Instance, maybe something went wrong during serialization

fluid wedge
#

alright

icy herald
fervent furnace
#

sad

icy herald
#

very

#

sad

rigid island
icy herald
#

actually idk, but in older versions everything works great

reef escarp
west lotus
reef escarp
# west lotus You seem to have been given enough relevant and helpful info in the forum thread...

They showed me how to make a pick up and put an item, only in the video there it shows how the item just lies after the throw button, but I need it otherwise, I wrote everything here - https://forum.unity.com/threads/pickup-item-and-place-item-system.1530037/#post-9545704 I don’t need to write code if you don’t want it, I need to at least know approximately how to do it approximately.

west lotus
elfin basin
#

So I'm noticing that OnCollisionEnters from my script are being called from all colliders in the children of my player. Is0 there a way to prevent this? I don't want my wheelcolliders to detect collisions from the street (causing player damage, when it's just driving on the road), but rather just the meshcollider on the player to do this. I don't want to have to put the script on the meshcollider, just the parent. Is there anything I can do here?

last quarry
#

Is anyone familiar with a bug in TextMeshPro where it does this?

#

The text input is correct

dusk apex
#

Does it occur if you do not use the new line character?

elfin basin
#

Align left?

dusk apex
#

Are there special invisible characters between e and l?

last quarry
#

No, and hardcoding the string makes no difference

#

(as opposed to getting it from a spreadsheet)

dusk apex
#

Does it occur only with level or any string beyond the fourth character?

last quarry
#

Only with Level

dusk apex
#

Does changing the font size a bit higher or lower affect this?

elfin basin
#

Are you typing it in manually or is it filled with code?

last quarry
#

Or just "el", really

last quarry
elfin basin
#

Does it do it with a default Ariel font?

last quarry
#

Only with this font

elfin basin
#

then it's the font.

last quarry
#

It's fine in other applications, so it's something to do with how TMP encodes it

elfin basin
#

Just go with another font

#

Can probably guarantee there are hundreds of fonts just like that one.

#

No need to spend the headache to fix that specific one.

#

It's generic "medieval style" font or whatever. RPG style, whatever you wanna say.

nimble cairn
#
    void Update() {
        if (Vector3.Distance(transform.position, targetInfo.Item1) < 1) sphereCollider.enabled = true;
    }

Is a line of code like this better in FixedUpdate()? The gameObject is a fast projectile.

I'm also not feeling too confident with Vector3.Distance(). Is there a more efficient method?

dusk apex
last quarry
nimble cairn
#

I apply an initial rigid body force on instantiation

nimble cairn
last quarry
#

Obviously that's gonna return the square distance but the square of 1 is 1 so nothing changes 🙂

subtle jungle
#
    private List<RoomInfo> cachedRoomList = new List<RoomInfo>();
            foreach (var room in roomList)
            {
                for (int i = 0; i < cachedRoomList.Count; i++)
                {
                    if (cachedRoomList[i].Name = room.Name)
                    {
                        List<RoomInfo> newList = cachedRoomList;

                        if (room.RemovedFromList)
                        {
                            newList.Remove(newList[i]);
                        }
                        else
                        {
                            newList[i] = room;
                        }

                        cachedRoomList = newList;
                    }
                }
            }
#

I've been getting the error "error CS0200: Property or indexer 'RoomInfo.Name' cannot be assigned to -- it is read only"

#

i have no clue what im doing wrong

fervent furnace
#

if (A=B)

subtle jungle
#

oh

#

i just realized i was missing an = sign

#

thanks

fervent furnace
#

btw newList and cachedRoomList are pointing same list

heady iris
#

Font Features, at the bottom of the "Extra Settings" section

gray raft
#

i am making a chess game, and i am highlighting tiles if it is empty but i want to stop highlighting tile if there is a chess piece how to achieve my game is 2d

last quarry
heady iris
#

Weird!

#

but maybe there was just a really mangled character in there

somber tapir
rain minnow
nimble cairn
#

So with the High-Fidelity URP asset apparently there is some sort of native motion blur?

#

Has anyone had experience with this?

gray raft
hexed pecan
#

Do you mean HDRP or is that a thing?

heady iris
#

nah, the high quality URP asset

nimble cairn
#

There are a few presets

heady iris
#

it's called "High Fidelity"

#

You might be seeing TAA artifacting. Motion blur would have to come from a volume

hexed pecan
#

My quick google didnt show anything relevant

heady iris
#

(although, isn't anti-aliasing configured entirely on the camera, not the URP asset?)

gray raft
#

if i share the code can you help with tha

gray raft
#

that

rain minnow
#

If you already have a way to check for when it's empty; use the same method to check for when it's occupied . . .

nimble cairn
#

@heady iris It's not TAA sadly

heady iris
nimble cairn
#

However, I've noticed that I can't turn off Motion blur during runtime. Even through the volume has been updated through code.

gray raft
#

if i do so , is doesnot highlight the tile in which there is a chess piece but highlight the tile after the chess piece, i want it should not highlight the row, if it founds that there is chess piece

#

i hope you understand of shall i share the code?

hexed pecan
astral nexus
#

sup guys, idk is it right place to ask
is using DefaultExecutionOrder attribute slow and bad? I know it doesn't change the script execution order settings, but applies it's effect at runtime
I like the idea behind this attribute (in dots there similiar stuff for executing systems), but idk is it worth using it or just create my own simple custom execution order system for my scripts?

hexed pecan
#

I would imagine that the attribute is used only once, not continuously

#

I would not worry about it

nimble cairn
#
MotionBlur motionBlur;
postProcessing.profile.TryGet<MotionBlur>(out motionBlur);
motionBlur.active = false;
``` @hexed pecan
hexed pecan
#

And remove motionBlur.active = false;

nimble cairn
#

Does not have a method .enable

hexed pecan
#

Sorry I was looking at the wrong thing (a parameter)

nimble cairn
#

xD

#

No worries

hexed pecan
#

Well, I do it the same way as you so not sure what's wrong

#

As a tip you could rewrite first two lines as just thiscs postProcessing.profile.TryGet(out MotionBlur motionBlur);

#

Make sure you don't have any other volumes in the scene that might take priority over the motion blur
Also could log profile.HasInstantiatedProfile() just to see if it uses a shared or instantiated one

rain minnow
sonic bone
#

not sure if this is the right channel to ask this question if it's not kindly redirect me to one.
So I was making a racing game and so I added a car and wrote some code to make that car work and it worked perfectly. The first video shows that.
But when I added another car to the game this happened (watch the second video).

#

I have no idea how to fix this please help 🙏

turbid surge
#

Im pretty new to zenject, I used to create a 'PlayerBase' class that would contain all the references to other parts of my player (PlayerController, PlayerInventory, etc.). I was thinking of introducing a GameObjectContext to it so I can inject other player dependencies instead of just filling the awake method with GetComponent<PlayerBlahBlah>() X amount of times.

#

Is that overkill or proper usage? thoughts?

fervent furnace
#

cant you assign them directly in inspector?

turbid surge
#

I could but I try to avoid doing that

#

it makes moving across scenes a pain as I believe doing that relies on the scenes meta data

spring creek
#

Where are you trying to use it? It's not c#

#

No off-topic jokes
Sorry

gray raft
spring creek
gray raft
fervent furnace
#

moving objects across scene will not lose the reference to any components in its subtree, unless you are referencing objects on other tree.

umbral oriole
#

How did i fix my 3d objects i guess pivot point, after i added a canvas, when i click on one of my 3d objects, i dont see the move tool on it but rather far away in the sky

vagrant blade
#

Make sure you're in pivot mode (not center) at the top of the scene window. Not a coding question either.

umbral oriole
#

Ah thanks, and sorry didnt check the correct channel

dusky pelican
#

Hello, what's the difference between ScriptableObject.CreateInstance and just constructing a class with "new"?

#

What I'm trying to say is, i have a class called "Gun" and it derives from ScriptableObject. So i want to use ScriptableObject as template class because i need to make some changes in "Gun" class at runtime then save it and load back.

delicate olive
#

Because the changes wouldn't persist unless you used the code in the editor (leads to compile errors in the build)

latent latch
hexed pecan
#

In a build I mean

leaden ice
#

If you want to copy a template, use Instantiate

dusky pelican
#

Basically, i think like this;

Create a Gun SO(So i can edit my gun easily in editor) ->
-> Edit Name, Damage, Price, IsPlayerOwnsGun in Editor
-> In Start(), create instance of class with SO values
-> If there is a save file exist, initialize Save File data's (If player owns gun, set the bool of instanced class)
-> Make some changes in instance of class(When player buys a gun, set IsPlayerOwnsGun true)
-> Serialize it and save it to JSON

#

So if i make like that, in the start should i use CreateInstace or something different?

leaden ice
dusky pelican
dusky pelican
#

Its looks like this

astral nexus
#

maybe it's beginner question type, but who knows
how to deal with "execution order race" of component's initialization (especially Awake and OnEnable problem) without script execution order feature in editor and not tightly coupling them together for checking if they are ready by polling/event? I've tried some sort of Monobehaviour manager, that gathers all monos and initialize them, etc., but it is still coupling with it and mono
static events = coupling too, so idk how to deal with it properly
maybe some tips or pointers what to search?

rigid island
#

esp DI part

#

if you need to mess with execution order of script then something might def be flawed in the structure

urban orbit
#

I'm making a Snake VS Block 3D Game. It's an endless game so my approach is to move the floors on the z-axis towards the player and just move the player on the x-axis. When the player touches a block the floor stops moving but the problem is that when there are multiple blocks side by side and the player moves between them, the floor movement resumes and it goes through the blocks without breaking them. How can I fix this?

mental rover
#

it seems like being stopped in place while the block is being broken is intentional?

urban orbit
#

I do want it to stop

urban orbit
mental rover
#

so I guess you want to continue allowing player movement on the x-axis, and have the block that's currently being broken update with the players position, the only thing going wrong is that the player can slip through between the blocks?

#

a fix will depend on how you're currently handling that collision

#

as an initial suggestion I'd make sure you're not updating the position with transform.position if you're relying on a rigidbody and colliders

#

but it could be due to several things

urban orbit
#

Oh, so the problem could be that I'm using Transform.Translate to move the floor?

urban orbit
mental rover
#

you could probably get away with it but you might need some more robust & explicit checks on overlapping colliders to stop the floor moving at all while you're wiggling left & right - perhaps in OnTriggerExit you can use https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html to double check you're definitely free of any other colliders before starting to move the floor again

tacit swan
#

if you define an int inside of a struct that inherits from ijob, whats the best way to modfiy the value of the int whenever you start a new job on another thread?

delicate garden
#

Is there a way to read an external asset during runtime? Like, let's say I want my game to have a folder "models" in it's directory, and it loads whatever files are in there and gives them to the mesh renderer on whatever object.

rigid island
#

Custom Method/Asset handler
||
AssetBundles/Addressables

swift falcon
cosmic rain
#

UnityAction is basically the same as Action. They work identically.

swift falcon
#
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

public class UnityActionExample : MonoBehaviour
{
    //This is the Button you attach to the GameObject in the Inspector
    Button m_AddButton;
    Renderer m_Renderer;

    private UnityAction m_MyFirstAction;
    //This is the number that the script updates
    float m_MyNumber;

    void Start()
    {
        //Fetch the Button and Renderer components from the GameObject
        m_AddButton = GetComponent<Button>();
        m_Renderer = GetComponent<Renderer>();

        //Make a Unity Action that calls your function
        m_MyFirstAction += MyFunction;
        //Make the Unity Action also call your second function
        m_MyFirstAction += MySecondFunction;
        //Register the Button to detect clicks and call your Unity Action
        m_AddButton.onClick.AddListener(m_MyFirstAction);
    }

    void MyFunction()
    {
        //Add to the number
        m_MyNumber++;
        //Display the number so far with the message
        Debug.Log("First Added : " + m_MyNumber);
    }

    void MySecondFunction()
    {
        //Change the Color of the GameObject
        m_Renderer.material.color = Color.blue;
        //Ouput the message that the second function was played
        Debug.Log("Second Added");
    }
}```
this code from the docs doesnt work ` m_MyFirstAction += MyFunction;` here
cosmic rain
#

It should work. Is that actually your code?

#

Share the code from your script file. Not the example.

swift falcon
#

i copied the exact code and it game me the errors

cosmic rain
#

That's not possible. Take a screenshot of your console window.

rigid island
#

Is the unity action have add listener ? Or is that only unityevent

#

Nvm only Unity event. Apparently

#

Never saw the point in UnityAction when you can just use the system.action

rain minnow
#

Unity just made their own (wrapper) versions of Action and Events . . .

rigid island
#

Right. Hmm UnityEvent makes sense cause the inspector advantage, Unity action kinda just sits there lol

loud wharf
#

Tbh, I never used Unity events. :p

#

Yet.

rain minnow
#

true. i bet they didn't want to break cohesion if they used System.Action . . .

#

unity events are awesome. i've grown into them . . .

loud wharf
#

Idk, I always managed to dodge them.

tacit swan
#

if i have a job

private struct FindPathJob : IJob 
{
  public int2 startPosition;
  public int2 endPosition;
}
#

whats the correct syntax for running that job and then specifying the two int2

rigid island
tacit swan
west sparrow
#

Just keep in mind, without a good hierarchy or structure, it can be difficult to troubleshoot later if you have a lot of complex ones (as figuring out who is disabling object X is no longer just a breakpoint)

west lotus
fervent furnace
#

i usually write on this way

JobHandle handle=new FindPathJob(){initializations}.Schedule();
west lotus
#

I have always disliked compacting things like that

#

At least when I write code I like to think of the next person that will have to read and extend it

lofty crest
#

trying to make a button press within an area be the trigger for dialogue

west lotus
lofty crest
#

so create a bool in OnTriggerEnter

#

then in OnExit set it to false

fervent furnace
#

ontriggerenter will be fired only once and you have to press the e at the exact same time (actually you will miss the keyup/down event since onXXX physics callback fired at rate at fixed update)

lofty crest
#

and in update i check if the button is pressed and check if the bool is true

fervent furnace
#

yes

lofty crest
#

and i guess i replace && Input.GetKeyDown(KeyCode.E)) with && bool = true?

fervent furnace
#

no, check if the player enter the collider by toggling a bool in on trigger enter and exit, then check the bool in update with the key down event

west lotus
#

Yes but you will have to define the bool in the class not the OnEnter function

lofty crest
#

ok so in the class, i write something like bool ButtonPressed = false;
then is on Trigger enter2d do i set it to true?
and exit2d i set it to false?

fervent furnace
#

yes, since on trigger enter only fire once, if player press e after he enters the collider the method will miss

lofty crest
#

do i just write something like bool ButtonPressed= true; in the Enter2d
and bool ButtonPressed = false in the exit?

#

and then in update what would i do exactly

fervent furnace
#

the bool should be renamed to eg playerentered, then check it in update

lofty crest
#

ok

lofty crest
fervent furnace
#
if(playerEntered&&e key down)
lofty crest
fervent furnace
#

read what uri have said

lofty crest
#

im still very confused.

#

also i tried renaming the bool and this is what i got

fervent furnace
#

show the screenshot, where you put the bool

lofty crest
#

@fervent furnace so here do i set it to true outside of the if statement?

fervent furnace
#

yes, but you have to check if the collider is player

playerEntered=collision.comparetag("player");
lofty crest
#

so if (playerEntered=collision.comparetage("player");
{
playerEntered=true;

}

fervent furnace
#

comparetag already returned a bool, dont need the if anymore (though it is still valid syntax)

lofty crest
#

and this is its own thing in ontrigger enter?

fervent furnace
#

only thing? yes

lofty crest
lofty crest
#

well Player with a capital P

fervent furnace
#

left the checking (and getkeydown) in update.....dont do it in OnTriggerEnter

lofty crest
#

using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class DialogueCharacter
{
public string name;
public Sprite icon;
}
[System.Serializable]
public class DialogueLine
{
public DialogueCharacter character;
[TextArea(3, 10)]
public string line;
}

[System.Serializable]
public class Dialogue
{
public List<DialogueLine> dialogueLines = new List<DialogueLine>();
}
public class DialogueTrigger : MonoBehaviour
{
private bool playerEntered = false;

public Dialogue dialogue;

public void TriggerDialogue()
{
    DialogueManager.Instance.StartDialogue(dialogue);
}

private void OnTriggerEnter2D (Collider2D collision)
{
    playerEntered = collision.CompareTag("Player");

    if (collision.tag == "Player") 
    {
        TriggerDialogue();
    }
    
}
private void OnTriggerExit2D(Collider2D collision)
{
    
}

}

#

this is the full thing

#

what needs to be done ?

#

@fervent furnace

fervent furnace
#

where is the update
and TriggerDialogue will be called right after the player enter the collider
finally !code

tawny elkBOT
lofty crest
fervent furnace
#
  1. detect if player enters the area then set the bool to true in triggerenter, reset it in exit
  2. check if player enters the area by that bool (setted in ontriggerXX) and check if player presses e in update
lofty crest
#

so for 1 first, in onTriggerenter, isnt that already done with the playerEntered = collision.CompareTag("Player");

#

i just need to add the playerEntered= false in exit

#

right?

fervent furnace
#
private void OnTriggerEnter2D (Collider2D collision){
    playerEntered = collision.CompareTag("Player");
    TriggerDialogue();<----
}
#

and the update is empty

lofty crest
#

private void OnTriggerEnter2D (Collider2D collision)
{
playerEntered = collision.CompareTag("Player");

    TriggerDialogue();
    
}
#

that is correct?

#

private void OnTriggerExit2D(Collider2D collision)
{
playerEntered = false;
}

#

and now just need to do update stuff

fervent furnace
#

yes, and you didnt check anything to fire TriggerDialogue()

lofty crest
fervent furnace
#

update

lofty crest
#

right so if(playerEntered=true && GetKeyDown(Key.code E))
{
TriggerDialogue()
}
?

#

something like that?

fervent furnace
#

yes

lofty crest
#

like clearly im doing something wrong

knotty sun
#

) in wrong place

lofty crest
#

right yeah im stupid

#

thanks

knotty sun
#

not stupid, careless which is even worse

lofty crest
waxen kayak
#

Ay guys, quick question

#

how can I modify a prefabs data in script

#

I have generated a list of prefabs, and they all have a component, which has a variable that I want to change

#
    public void GetSaveableIDs()
    {
        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        stopwatch.Start();
        int counter = 0;
        for (int i = 0; i < saveablePrefabs.Count; i++)
        {
            if(saveablePrefabs[i].TryGetComponent<SaveObject>(out SaveObject saveObject))
            {
                if(saveObject.ID != i)
                {
                    saveObject.ID = i;
                    counter++;
                }
                PrefabUtility.RecordPrefabInstancePropertyModifications(saveablePrefabs[i]);
            }
        }
        stopwatch.Stop();
        Debug.Log($"Updated {counter} IDs in {stopwatch.ElapsedMilliseconds}ms");
    }
#

this does not work.

leaden ice
#

Wrong thing entirely

waxen kayak
#

oh it has to be prefabInstance and not GameObject?

leaden ice
#

Typically EditorUtility.SetDirty or asset database.save etc

leaden ice
#

Prefab instances are the copiea of prefabs in a scene

waxen kayak
#

ooooh

leaden ice
#

This is the original prefab

#

It's not a prefab instance

#

So some function that deals with prefab instances is inappropriate

waxen kayak
#

okay then replacing "PrefabUtility.RecordPrefabInstancePropertyModifications(saveablePrefabs[i]);" with "EditorUtility.SetDirty(saveObject);" is correct?

leaden ice
waxen kayak
#

I'll try that

#

it works, thanks

round violet
#
RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.right), out hit, Mathf.Infinity, _ladderLayerMask))
        {
            Debug.DrawRay(_ladderClimbingRaycastPoint.position, transform.TransformDirection(Vector3.right) * hit.distance, Color.yellow, 10);
            return true;
        }
        else
        {
            Debug.DrawRay(_ladderClimbingRaycastPoint.position, transform.TransformDirection(Vector3.right) * 500, Color.blue, 10);
            return false;
        }

any ideas why the raycast doesnt hit anymore close to the top ?
the whole grey rectangle is one gameobject with the "Ladder" LayerMask on

leaden ice
#

Raycast is using transform.position
DrawRay is using _ladderClimbingRaycastPoint

#

You probably meant to use _ladderClimbingRaycastPoint for your Raycast

round violet
#

forgot to check if i changed all before testing

long saffron
#

Hello I am trying to get instantiate to load multiple objects in, but then it quickly scales up. Tried to set a wait in the function but it doesnt seem to be working

gray mural
#

You mean, they spawn to fast?

long saffron
#

yeah a lot

gray mural
#

Haven't you written your code this way?

long saffron
#

------------------------------------------------------------------------------------------- IEnumerator SpawnTargets()
{
Vector3 randomSpawn = new Vector3(Random.Range(-5, 5), Random.Range(3, 5), Random.Range(-5, 5));
Vector3 randomSpawnTwo = new Vector3(Random.Range(-5, 5), Random.Range(3, 5), Random.Range(-5, 5));

//yield return new WaitForSeconds(easyDelay);
if (difficulty == 0)
{

    Instantiate(targetPrefab, randomSpawn, Quaternion.identity);
    yield return new WaitForSeconds(easyDelay);

}
else if(difficulty == 1)
{
    Instantiate(targetPrefab, randomSpawn, Quaternion.identity);
    Instantiate(targetPrefab, randomSpawnTwo, Quaternion.identity);

    yield return new WaitForSeconds(mediumDelay);
}

}-------------------------------------------------------------------------------------------------------------

#

When i put the yield wait for seconds after the instantiate it seems more reasonable

#

just not sure if therers a better way

fervent furnace
#

ofc you need to wait then instantiate, not spawn the object then wait and do nothing

long saffron
#

the difficulty is more tame now

safe laurel
#

!code

tawny elkBOT
gray mural
gray mural
#

haven't noticed it haven't popped up

long saffron
#

not sure, just what people use in IEnumerator

#

only way ive seen to wait and it actually works

gray mural
#

Do you call SpawnTargets multiple times?

#

well, sure you do.

#

then how do you expect it to work?

#

If you want them to spawn one-by-one or two-by-two, you'll have to call a single coroutine every time you click, I suppose

long saffron
#

I call spawntargets at the start and whenever one gets destroyed

#

cs

#

IEnumerator DestroyTarget()
{
yield return new WaitForSeconds(destroyDelay);
Trainer.targetsMissed = Trainer.targetsMissed + 1;
if(Trainer.gameOver == false)
{
Trainer.instance.CallSpawnTargets();
}
Destroy(gameObject);
}

private void OnMouseDown()
{
Trainer.targetsHit = Trainer.targetsHit + 1;
Destroy(gameObject);
if(Trainer.gameOver == false)
{
Trainer.instance.CallSpawnTargets();
}
}

gray mural
#
private IEnumerator SpawnTargets(int count, float interval)
{
    WaitForSeconds spawnWFS = new(interval);

    for (int i = 0; i < count; i++)
    {
        Spawn(); // your stuff        

        yield return spawnWFS;
    }
}
#

let it look like that

long saffron
#

how would a for loop work

#

with the count

gray mural
long saffron
#

But that does look cleaner

gray mural
long saffron
#

oh nvm, and the code would look a little cleaner if i can implement that

gray mural
#

nothing hard to implement

long saffron
#

I want to spawn independently of anything

gray mural
long saffron
#

ok will try that out thanks

gray mural
#

feel free to ask additional question about this issue.

restive ice
#

I have this SerializableDictionary<TKey, TValue> class that takes in a List<SerializableKeyValuePair<TKey, TValue>>

it seems if I add a List<UnityEvent> as the TValue, I only serialize one of the events?

#

i would expect a count of 2 events in the PlayerAccusedRustles part

gray mural
restive ice
#

my serialized list has 2 events

#

but when I initialize the dictionary that list is only of length 1 ?

gray mural
fleet furnace
restive ice
gray mural
fleet furnace
restive ice
#

here's a simpler example:

#
public class Tester : MonoBehaviour
{
    public SerializableDictionary<int, List<string>> Dict;

    private void Awake()
    {
        Dict.TryGetValue(1, out var list);
        Debug.Log(list.Count);
    }
}
#

this outputs count 2

fleet furnace
restive ice
fleet furnace
restive ice
#

yeah but you can see that the count is one

#

oooh wait im being silly

#

an event already supports 'multiple events'

#

so this value is a List<UnityEvent>

#

but the UnityEvent itself contains 2 methods to invoke

#

so the list part here was irrelevant

#

and indeed length 1 long as it was supposed to be

long saffron
#

For some reason its spawning a lot when I have only 1 instantiate statement

#

'''cs

#

private IEnumerator SpawnTargets(int count, float interval)
{
WaitForSeconds spawnWFS = new(interval);
Vector3 randomSpawn = new Vector3(Random.Range(-5, 5), Random.Range(3, 5), Random.Range(-5, 5));

  for (int i = 0; i < count; i++)
  {
      Instantiate(targetPrefab, randomSpawn, Quaternion.identity);

      Debug.Log(i);
      yield return spawnWFS;

  }

}

#

'''

#

StartCoroutine(SpawnTargets(10, easyDelay)

knotty sun
#

you are telling it to spawn 10 times

long saffron
#

also i have the coroutine in the update function

spring creek
long saffron
#

lol yeah

knotty sun
#

And your surprised you get more than 1?

long saffron
#

yeah

#

its spawning appropriately now

#

Didnt notice it in the update

tacit swan
#

I have a behavior tree and it only has one node which is a pathfinding node. When this node is called, will it keep calling the pathfinding over and over again therefore decreasing performance?

spring creek
#

So there is no reasonable answer to your question without knowing more.
Other than saying profile it

tropic jewel
#

https://hastebin.com/share/tabetewatu.java hi,
I'm currently working on a mobile fps game that involves joystick movement and camera rotation. Each function works actually perfectly well independently but the issue is when I initiate one action and then attempt to perform the other action (ex: rotating the camera) simultaneously. The controls become 'glitchy' in a way they are not as intended.
I would really like a hand of help , would really appreciate it

rocky jackal
#

i have this weird situation, i have a function to convert the time from 24h to a value between 0 and 1 0being sunset 0.5 being sunrise...
For some reason if i enter 18 in this function it gives me back 0.75 eventho it should be 0

#

it always returns 0.75 for some reason

spring creek
#

0 should be 0, and 24 should be 1, right?

rocky jackal
#

but why doesnt the function return 0 ?

spring creek
rocky jackal
#

it is

rocky jackal
tropic jewel
spring creek
rocky jackal
#

i fixed it by changing it to 1/24.0f

spring creek
tropic jewel
#

sorry

delicate olive
loud burrow
#

!code

tawny elkBOT
loud burrow
#

I'm having trouble raycasting to a mesh that I've generated. In my scene I have an empty gameobject called "worldmanager" that spawns a procedural mesh with the scripts WorldManager.cs, Container.cs, and Voxel.cs. I have them linked below. The mesh generates how it is supposed to and looks fine. With my script PlayerInteraction.cs, I do a raycast out from my player cam. this raycast hits a triangle in the mesh and determines which voxel it belongs to in the mesh. This script works perfectly when I raycast to faces of the mesh that point in the positive x, y, and z directions but not in the other directions. When looking at the bottom of the mesh from below(Me facing the negative Y direction, face of the mesh towards the positive Y direction) I can delete as many voxels as i want but not when trying to raycast off of faces facing in the positive directions.

Voxel.cs - https://hastebin.com/share/wuluvehilu.csharp

PlayerInteraction.cs - https://hastebin.com/share/ubiguxukuy.csharp

WorldManager.cs - https://hastebin.com/share/fikinuhoxi.csharp

Container.cs - https://hastebin.com/share/kimikihiju.java

storm thorn
#

Is there a way to save the playing time of the player and make it be seen on the UI? so that when they get back, they know how much time they played; I'm using firebase for my backend

rigid island
#

there are usually more than a way

#

just use an int

#

or float

#

then convert it to a time

storm thorn
#

What about when we have total of five games in one app, and I want to record the time they spent on one game?

rigid island
#

same thing

#

store each number for each game?

storm thorn
#

I also have login and registration

rigid island
#

what about it

storm thorn
mossy snow
#

what's the issue? if you already have login with firebase, keep track of those values in firestore

rigid island
#

personally for such simple thing I would just use the Unity built in cloud save

#

since you can link a specific login to specific data automagically

storm thorn
storm thorn
storm thorn
#

Okay! Thank u to the both of yall!

cunning radish
mossy snow
#

assuming it's a serialized property, usually you'd use PropertyField

cunning radish
glass fossil
#

Not sure how basic or advanced this is so I'm here.

I'm trying to use c5 library in my project. I followed the instruction unity has up on importing libraries.

In vs2022, I had no issue adding it but unity throws an error over its namespace being used. Within unity, the folder with the dll's doesn't show up but it does in vs2022 and windows.

Should I have not installed the library through the vs2022 package manager?

This is what I used as a guide to get unity to work with it. Is this not what I need?

https://docs.unity3d.com/Manual/dotnetProfileAssemblies.html

calm talon
#
    private IEnumerator SpitAnim() 
    {
        animRunning = true;
        acidAnim.enabled = true;
        float speed = totalLengthOfProboscis / timeForAnim;
        for (int i = 0; i < joints.Count - 1; i++) 
        {
            acidAnim.transform.parent = joints[i];
            acidAnim.transform.localPosition = Vector3.zero;
            float timeToCross = joints[i + 1].localPosition.magnitude / speed;
            for (int x = 0; x < animIterations; x++)
            {
                acidAnim.transform.localPosition += joints[i + 1].localPosition.normalized * speed * timeToCross / animIterations; 
                yield return new WaitForSeconds(timeToCross / animIterations);
            }
        }
        acidAnim.enabled = false;
        animRunning = false;
    }

I have some code in a coroutine that manages an animation of a circle going through some joints for my object. The code runs fine at low values for iterations and takes the correct time to complete, however when I increase the number of iterations the time it takes to complete also increases when I want it to remain constant

#

(the time the function overall requires to complete, not the value itself)

leaden ice
#

You'll need to use your own float timer and Time.deltaTime

#

And yield return null

calm talon
#

could you give an example?

leaden ice
#

Not really because I'm on my phone

calm talon
#

alright, I think I have an idea of how to do it anyways

#

thanks for the help mate

#
            float timeToCross = joints[i + 1].localPosition.magnitude / speed;
            float timer = 0;
            while (timer != timeToCross)
            {
                timer = Mathf.Min(timer + Time.deltaTime, timeToCross); 
                acidAnim.transform.localPosition = speed * timer * joints[i + 1].localPosition.normalized;
                yield return null;
            }
#

yep, this does the trick

radiant elm
#

Does anyone know why my two bone ik constraint weight gets set to 0 when disabling and re-enablign an object that has it as a child?

#

And is there a way to fix it?

delicate olive
radiant elm
#

thx will post there

strange gust
#

how would i do momentum/acceleration for a rigidbody

rigid island
strange gust
#

and momentum?

#

would that be the same

rigid island
#

just need to use the correct method to move (the one mentioned above)

strange gust
#

what about slope momentum, would it just be adding force on the slope direction

rigid island
#

it will go up the slope but slow you down

strange gust
#

yeah

smoky pike
#

I have an async function that returns a string:

`

public async Task<string> GetPaginatedScores()
{
    Offset = 10;
    Limit = 10;
    var scoresResponse =
        await LeaderboardsService.Instance.GetScoresAsync(LeaderboardId, new GetScoresOptions{Offset = Offset, Limit = Limit});
    return JsonConvert.SerializeObject(scoresResponse)
    Debug.Log(JsonConvert.SerializeObject(scoresResponse));
}

`

#

In my Awake() method I have:
`
string scores;
public async void Awake(){

    scores = await getPaginatedScores();

}

`

#

However, whenever I Debug.Log the scores in my Start() method, I get Null

#

How do I wait until I receive the scores before I display them in the game

cosmic rain
smoky pike
cold parrot
#

whats in your start()?

smoky pike
#

`
async Start(){

Debug.Log(scores);
}
`

cold parrot
#

i would consider an async awake a code smell, its supposed ot behave like a constructor and shouldnt really be async

#

why don't you do your async stuff all in start?

leaden ice
smoky pike
cold parrot
#

it generally makes little sense to spread async calls around, you'd usually want to make one async call in one place and then inside that call sequence/await your async operations

smoky pike
cold parrot
#

awake should be used for local init, start should be used for actually doing stuff

smoky pike
#

oh ok i got that confused thanks

glass fossil
#

So I'm trying to setup an A * algorithm that handles pathfinding within a system of waypoints. I've run into many issues trying to do this and I'm wondering if there might be a simpler approach to this while allowing modularity of the amount of waypoints. I don't want my object to move directly to a waypoint unless its a direct neighboring waypoint, I want it to create a path based on the shortest distance via the network of waypoints (sound like an A* to me). I should add, any point between two connected waypoints is also intended to be a valid target for movement.

Can someone point me in the right direction? What I have now is causing unity to hang and I end up force closing every time I test my pitiful attempts to debug.

Is there a better method considering the final project will have hundreds of waypoints in the network but I cant even work with 4 to 12 at the moment?

I've checked for infinite loops and all that jazz. I must be stupid, totally missing something, or this method just isnt going to work.

lean sail
leaden ice
#

if Unity is hanging you either have written it very inefficiently or have managed to create an infinite loop somewhere

#

Or you have way too many nodes

glass fossil
#

ill try using the debugger again. I have checks in place. I cant find a loop anywhere. i have been feeling like i may be writing things inefficiently.

nimble cairn
#

IEnumerator activeCoroutine;

activeCoroutine = StartCoroutine(Test());

StopCoroutine(activeCoroutine());

How do I convert type coroutine activeCoroutine to IEnumerator to achieve the above mentioned code?

lean sail
glass fossil
#

*infinite loop

lean sail
#

And its type Coroutine

glass fossil
#

i'll try with a fresh project with just the bare bones to test this. if i end up with the same issue there, ill start a thread and maybe someone can point out my lackluster coding lol

lean sail
glass fossil
# lean sail Should be enough really to just make a new scene and use the debugger in VS

ive tried a few things. using the debugger and recreating the hang doesnt yield any information. its as if unity is fine. nothing in output, no breakpoints. the last log in unity's console is the last move i made before giving it the next input. whats odd is it doesnt do this if im going back and forth between the same 2 nodes. only when i have at least 3 unique moves.

cobalt gyro
#
using UnityEngine;
using System.Collections.Generic;
using System;


namespace Blood.AI
{
    public class PathRequestManager : MonoBehaviour
    {
        Queue<PathRequest> requestQueue = new();

        PathRequest currentRequest;

        public static PathRequestManager instance;

        Pathfinder pathfinder;
        bool processingPath;
        private void Awake()
        {
            instance = this;
            pathfinder = GetComponent<Pathfinder>(); 
        }
        public static void RequestPath(Vector2 pathStart, Vector2 pathEnd, Action<Vector2[], bool> callback)
        {
            PathRequest newRequest = new PathRequest(pathStart, pathEnd, callback);
            instance.requestQueue.Enqueue(newRequest);
            instance.TryProcessNext();
        }
        void TryProcessNext()
        {
            if (!processingPath && requestQueue.Count > 0)
            {
                currentRequest = requestQueue.Dequeue();
                processingPath = true;
                pathfinder.StartFindPath(currentRequest.pathStart, currentRequest.pathEnd);
            }
        }
        public void FinishedProcessingPath(Vector2[] path, bool success)
        {
            currentRequest.callback(path, success);
            processingPath = false;
            TryProcessNext();
        }
        
    }
    public struct PathRequest
    {
        public Vector2 pathStart;
        public Vector2 pathEnd;
        public Action<Vector2[], bool> callback;

        public PathRequest(Vector2 pathStart, Vector2 pathEnd, Action<Vector2[], bool> callback)
        {
            this.pathStart = pathStart;
            this.pathEnd = pathEnd;
            this.callback = callback;
        }
    }
}```
#

for some reason whenever i put this monobehaviour on an object playmode wont load and i have to close out unity through the task manager

leaden ice
cobalt gyro
#

none of it breaks the editor

#

this script isn't freezing on runtime

leaden ice
#

You just said it was freezing in playmode:

playmode wont load and i have to close out unity through the task manager

cobalt gyro
#

what i see

#

its freezing just before playmode

leaden ice
#

Yes, that looks like an infinite loop

leaden ice
cobalt gyro
#

ty

#

hope i can fix it

solemn shale
#

I keep getting this error across multiple projects, independent of whether or not I have any compiler errors in the code I write myself. I'm 99% sure this is just a bug with Unity itself. It doesn't stop me from entering play mode or running code, but it's still super annoying.

cobalt gyro
solemn shale
#

That seems really extreme so clearly no.

cobalt gyro
#

restarting your computer?

solemn shale
#

Restarting computer doesn't help, it keeps coming back. I did recently update Unity hoping that would fix it but it didn't.

#

It seems like something related to Unity's own internal UI

spring creek
solemn shale
#

So just literally delete this entire folder and that won't have any negative consequences?

spring creek
#

There is nothing you made in there (I guess unless you made VERY bad choices lol). It is a cache of generated files. They will regenerate when reopening Unity

solemn shale
#

Am curious why it does this to begin with

spring creek
earnest gazelle
#

I have a data structure class called Voxel. To save a voxel world, do you prefer to create a different separate persistent data structure or not, I mean save it as Voxel type itself?

 [MessagePackObject]
    [BurstCompile]
    public struct Voxel : IEquatable<Voxel>
    {
        [IgnoreMember] public const int SettleThreshold = 10;
        [IgnoreMember] public const byte EmptyId = 0;
        [IgnoreMember] public const byte ModuleVoxelId = 1;
        [IgnoreMember] public const float LevelStep = 1f / MaxLevel;
        [IgnoreMember] public const byte MaxLevel = 4;
        [IgnoreMember] public static readonly Voxel Empty = new
        (
            id: EmptyId,
            isVoxel: false,
            blockType: VoxelBlockType.NonBlock,
            moduleVoxelType: ModuleVoxelType.None,
            color: Color32Utility.White,
            state: VoxelState.None,
            settleCounter: SettleThreshold,
            level: 0,
            isFluid: false
        );
        // Some properties (ignore member)
        [Key(0)] public int Id;
        [Key(1)] public int Color;
        //etc.

or another data structure

[MessagePackObject]
public struct VoxelPersistentData
{
    [Key(0)] public int Id;
    [Key(1)] public int Color;
}

lean sail
earnest gazelle
#

even if that class Voxel is a data structure and contains just data but there are some props depending on others, so if I don't create another class, I should add IgnoreMember attribute to ignore it. Also, as you mentioned if I create a separate data structure to keep persistent data, storage classes work with these neat data structures and not main data structures

swift falcon
#

Alright, this isn't unity specific just coding in general.
What I'm trying to do here is have a pre-defined profile with the ship using one of the possible fields from the profile
say the profile has "a" "b" and "c" as possible ship names, then the ship will have one of those names

What I'm wondering is if this implementation has any problems with it or issues that could happen in the long-run?

earnest gazelle
#

About renaming, I use key ids instead of field name. So, renaming would be OK

lean sail
lean sail
knotty sun