#archived-code-general
1 messages · Page 242 of 1
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.
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{};
🤔
was your field previously serialized as [field: SerializeField] public string previousName {get; set;} or something?
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
ugh my head hurts from trying to think about this for so long.
I really appreciate your help tho, i just don't understand whats the whole point even, then.
Cause then modularity here loses all its significance.
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"?
As in not all players have a RegenStat? You can simply check that via init method and not set it
No point to make a RegenPlayer : Player* class ;p
I don’t think you’re getting me again. Ugh it’s so hard to explain.
scriptableobjects are optimized as data structures c++/cpp internal, monobehaviors a bit slower but in framework of game c#, you better let data in scrptableobjects
Player is a mono for the reason that it exists in the scene, otherwise I'd make it a plain class
Ok it works, as long as you specify correct variable with this attribute it seems to be doing fine.
you have already the connection into scriptableobject, playerSO.HealthStat just push property there in so
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
unityevent event delegates and action behaviour into scriptableobjects can do a bit org
Yeah, just check when you drop an item onto your inventory such that
if(objectdropped is Item) but you need to be more discrete to prevent items such as dropping a sword into your boot slot
yeah, I would do it through my dropHandler right? also why is UI so hard compared to everything else
oh yeah fogot to add the dot operator. I'm just typing this in discord
i have a working inventory from a tutorial but i barely understand the UI part
How do you make disparate systems in your application work together? Learn how to use ScriptableObjects as event channels in your Unity project.
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
Isnt this code wrong?
Constructor should not assign anything to SO, but its own property right?
i.e. instead of playerSO.regenStat = new...
It should be
regenStat = new...
move from class Player -to> PlayerSo :: float healthStat; RegenerativeStat regenStat;
Player is a mono. I am makign a new regen object but taking the value that I would put into it set by the SO
oh wait im dumb you're right
yep I was worried for a second that this is correct, after all I've been through with SOs lol
im reading comments above thinking I missed something, but I added on dot operators
Yes Player is MonoBehaviour because you use it as component in gameobject, but other 2 variables.
yeah, like do you know why I need a "Canvas Group" and a "Layout element" for my inventory slots, what do those even do
I suggest youtube videos for that
coud be also a course or video c#
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.
I completely understand the inventory system, its just the UI part
and not because of the logic, just the unity stuff
So what is the issue with UI?
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;
Whenever the z position of the code does not = 0, the object does not fall: https://pastecode.io/s/nk7hkgkr
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
Which tutorial are you following?
dapper dino
monkey code
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
wait maybe i'm thinking about it wrong
Basically prevent item from being dropped on a slot.
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?
well idk, I always try to separate UI and logic and only use Events.
yeah I did
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.
so don't parent and set trasnform within the UI code?
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)
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?
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.
alright, makes sense
what youtubers do you recommend to watch to learn these things?
if you're using drag features like mouse or finger then youll want to look into IPointerHandler and IDrag interfaces
yeah i'm using those
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?
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.
id skip the design and just get it functionally working
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
that was a song code money, dirty code just do it (profiler but testing games gives result ) no need to explain assembly
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
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.
ALT + TAB
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.
remove it then put it back on the GameObject real quick...
if you switch the application into a unknown example calc, it schould detect , than ALT+TAB again and recompiled auto
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.
I cant, because it cant find the script.
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
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.
same name of script, has to be to get back the values (for example in scriptableobjects) have you rename, back
There are no compile errors tho(not until I start the game)
does the script name match the class name?
Yes
So this issue happened when I moved scripts around to organize and after I restarted Unity.
rename back and copy the code, into a new renamed class
than copy values from one to other, prefab/so
if you rename you loose values of inspector
put the script in the Assets (root) folder then try to add it once again to verify.
How did you move the files around?
In VS2022 I moved them to a different folder
I guess that was a mistake
Use Unity to move your files and create folders; it brings the meta files with it . . .
this talks about how to orginize your files properly in any case: https://docs.unity3d.com/Manual/SpecialFolders.html
sounds like its time to consider a version control system XD
Either way there are no meta files in Assets folder, everything was moved
(git, plastic)
I do have it, but I dont want to restore all of the changes lol
It's probably because you cleared FSM.bitingfish the first time you find one
omg that probably is it tysm
is there really no magic button to remove meta files and recreate them, I dont mind assigning scripts manually to each game object 😄
No problem! Sometimes a second set of eyes can help
if you try to F2 the class name in VS, does that rename the file name as well in the Editor?
You probably need to regenerate your library files . . .
How can I do that?
1 sec, trying
it works!!! you are my new favorite person
either from the editor, or simply deleting it, then reopen Unity
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
which means they probably aren't exactly the same name...
guess I needed to alt tab, either way renaming file in VS renamed it in the Unity.
in code editor of vs 2022 s/he means to press F2 to rename a method/class (class rename changes files correctly)
You have to let Unity finish recompiling for it to update . . .
or right click a class name
that's a good thing!
auto-save-scenes on play in settings is also a incl. feature, Preferences -> Generals
so do be clear, do I remove Library folder?
niche!
Renaming class didnt fix the issue
worth a try I'd say....
sometimes simply restating Unity does miracles!!! (don't tell anyone!)
continues with on build it does auto save
I tried that, in my case Restarting Unity caused this issue to happen
It worked fine before I restarted :x
that's a... miracle, too!
restart all devices even cars of today, take battery out and reboot, than update fixes all (bugs)
I wish Unity was smarter
Soon™️
actually if i see so many packages and versions its a miricale how they go fine in c# (not like pyhthon jova breaks)
It is better for it to not make assumptions
Did you delete the library?
Yeah its doing Unity things now, loading a project
Python be like: Backward compatibreaks
Going to take a while
Close out of your editor and Unity. Everything. Load the editor back up, click on a script to open it in your IDE . . .
oh like that
reimport all is a bit dangerous (but in case your game is missing smth you could check / dependence packages upd )
I think removing library might be a fix, I just need to reassign things in inspector
We tried reimport all and it didnt do anything
have you give your project to other gamedev, so check the unity version ( downgraded 2019 ? )
@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!)
its weird that even after removing Library, it didnt remove all from inspector, only broken scripts I think.
what a doubling down situation...
no it definitely wasnt that, it broke on my side first
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
I wonder if that would have fixed the issue...Can you run any of that code with compile errors?
not sure tbh, but that's what is responsible of compiling the scripts.
if you have another version of unity even a beta than you could copy the project and see is there same error or auto fixed
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.
do you mean to "update" unity version so some Unity magic would fix the issue?
We are on the latest 2022, so there isnt much we can update to.
witchcraft magic in code
I dont think I ever tried to downgrade tho, but I'd rather not risk more issues lol
yes, but the option would have been you copy the repaired into the working main project if its fixed in code
deprecated
make a copy of the script content, and paste in a newly created script maybe?
what next? install a v8 engine?
Yeah copying the script was my last resort really
not yet unity 6 (great graphics and better c#)
As I would have to redo quite a bit of them
defo!
save your 50 cents, woud have been a arcade machine world of games
void SpawnObjects()
{ numberOfObjects = objectPrefabs.Length ; // add this, is'nt it fixing spawn obj? ```
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
'''cs
void SpawnObjects()
{ numberOfObjects = objectPrefabs.Length ; // add this, is'nt it fixing spawn obj? test '''
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)
What does that even mean?
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
If that's what you said, that's what you would have written instead of whatever that previous splurge of words was
You can get the contact point:
https://docs.unity3d.com/ScriptReference/ContactPoint.html
Nevermind, you're using triggers. Trigger collision doensn't give you contact points.
I was gonna suggest raycasting, but I see that is the top answer there. So I just second that
ok thanka
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
Scriptable objects aren't intended to be mutable.
The normal use-case would be having non mutable data that are independent of the Game Object
Scriptable objects do not exist as assets in the build so you'll create instances of the scriptable object if you mutate it - others may be referring to different instances of the SO.
ie References between scenes of mutated SOs will likely be referring to different instances.
well i'm not changing anything during runtime
Your VoidEvent might suggest otherwise but alright.
im changing the ItemContainer but not the inventory itself no?
If you're simply going to be referencing something not related to any scene, it should be fine.
what do you mean?
I don't know anything about your program, so just
..
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
is the gameobject moved to ddol scene after you enter play mode?
nope the UI in the loaded scene is getting destroyed after i click to load in the main Scene
have you checked the console?
yes i tried debug.log but no clue
is the canvas root object?
btw not debug.log but to read any messages/warnings/errors
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
raycast to see if the screen ray hits the "area" (collider)
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/*
Are you sure it didn't work? Changing the gitignore doesn't automatically stop tracking new ignored items.
Yeah. I deleted everything and then added a new file to check
Like now in git remote repo I have "Дім" and "Гравій". But other things are ignored in git status --ignored
So the problem is that things are being ignored that shouldn't be
this is neither unity nor code related, by the way..
Um. But yeah. I just don't know where to ask those things😅
Stackoverflow too slow to ask this things
But all programmers are using git, so I thought to ask here
https://git-scm.com/docs/gitignore
It is not possible to re-include a file if a parent directory of that file is excluded.
It’ll be a pain, but you’ll have to exclude each individual folder under the parent you want want to exclude
Actually I just found this which might be what you want https://stackoverflow.com/questions/2820255/how-do-negated-patterns-work-in-gitignore
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?
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?
dont crosspost, stick to #💻┃code-beginner
oh sorry I didn't see that channel
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
In a MonoBehaviour script:
public List<CardData> myCards;
// Drag your SO's into the inspector
So I need to manually create a list of SO's in the inspector? That seems very inneficient. Is that really the best way? I'm going to have hundreds of cards
what inefficient dragging a bunch of assets in a slot ?
Nothing wrong with loading them automatically from Resources in this case IMO
it takes like 2 sec. You can also make another ScriptableObject 'CardCollection' with a:
public List<CardData> Cards;
That way you only need to create 1 list and can share that around in case you need to have access to your cards in multiple scripts.
I've heard that loading from resources is slow, but if I make the list of cards when the game starts and hold them in memory, that would circumvent the slow load times, correct?
Yeah you would only load them once
Can also just load a single SO that just holds references to the card SO's
would that be more efficient or about the same in terms of memory?
Probably the same memory wise
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
what are you trying to store?
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?
You shouldn't destroy things unless you will never need them again in the scene, disable them instead.
The script that spawns them could put every instantiated car in a list and then call a method on them that handles the stopping part.
Or the cars subscribe to an event from the gameLoop and do something when that event gets invoked.
I understand that you speak of object pooling,
but the last sentence you said about subscribing to events means that the script keeps running in the background for each car, listening to the game ended event. is that right?
or do you mean enabling the script at start of game?
that would make more sense
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.
well, a Car should probably handle both the accelerating and the braking, maybe a bool in Update() checks which of the two is should do. When the event gets triggered it toggles the bool and the car starts doing the other action.
i was hoping I could do something ASPNET style and use zenject to inject a dbRepo service and get my info that way
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
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
hey guys what do i do if im having an issue with a game which is runned on unity?
Then contact the creator through support chnnels
its a game created by a singular person and i have no ways of contacting him sadly
Then you're out of luck
;-;
Oh Sorry Idk if i how to do inject in Unity I'm more familiar with regular asp.net with that
can't you just use a DLL/ external Library?
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.
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
yourUIElement.transform.localPosition = gameObject.transform.position;
*I think
didn't work, already tried 😦
https://forum.unity.com/threads/create-ui-health-markers-like-in-world-of-tanks.432935/ this might help you.
nvm, you can just use:
uiElement.transform.position = targetT.position;
without any converting. @rough sorrel
but that would make the uiElement be like in z=-100000, so it wouldn't be visible
thank you
you could keep the .z position of the ui element and only use the x and y of the target.
then it doesn't follow the correct position haha
with that it only does like a shadow
mhh ok I only tested it in 2d
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
You can call StartCoroutine on any MonoBehaviour reference
You could have a script/MonoBehaviour in the scene whose sole responsibility is to run coroutines for your nodes
yea i realized even if the node class wasn't on the gameobject i could reference classes through the behavior tree and pass them onto the node class
tyty
btw can you use both dots and the normal oop method in the same project or does it get too messy usually
You can do that. It does get messy if not done carefully
It depends on the context of course
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
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...
It could be that I'm getting the pixel billinearly?
Then again I'm doing that with each texture so it should be relative
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 ```
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?
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
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.
In the following script how can I get the path to the script in the Assets folder?
using UnityEngine;
using System.Reflection;
using System.IO;
using UnityEditor;
[InitializeOnLoad]
public class
I will create a Singleton or similar at game start and initialize it. Let me see if that works.
True, if the object it not actually used in the scene then it may not be included in your build
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.
well, what line is it on?
you need to know where the error's coming from if you're going to fix it
says its on the GameObject otherOBJ = other.transform.parent.gameObject; line
also #💻┃code-beginner
sounds like that object doesn't have a parent, then
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
transform.parent is looking for a transform on a parent
if there is no parent, its null
yes because the weapon object i was finding through that line has a parent that has the script
you should probably clean these up with some Components
yes: references stored in variables you assign in the inspector
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
instead of just searching for components and hoping they're in the right spot
i don't think you understood what navarone suggested
you do have "sword2Parent" and "basicSoccerBall" at least
if(other.TryGetComponent(out sword2Parent sword))
sword.damage
oh wait wth is this
GameObject.Find("soccer ball").GetComponent<basicSoccerBall>().damage;
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;
}
}
avoid
GameObject.Find
oh ok
kinda made it slightly less worse
you dont need the switch for the first two
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
but the scripts im getting damage from have different names
but they all have only those components..
so the tag is kinda pointless no?
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
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
interesting... im just gonna stick with what i have for now though because i need to get this game done before christmas
alr. any further question though should go in #💻┃code-beginner
this channel assumes you know this stuff
I think this belongs to #🤖┃ai-navigation
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
For us to help you, we would need to know the very specifics of your inventory system, else this would be very hard to answer
I want to make a mechanic for picking up an item like in the (horror game within) https://pollero.itch.io/the-horror-within
there are dozens of different ways to do this
But you could do something like this maybe:
- Shoot a raycast from the player's camera straight forwards and if it hits an object that's hittable, continue to the next step
- Display some ui and prompt the user to press "E" for example to pick the item up
- When "E" is pressed, disable rigidbodies for example and teleport the object to the hand
- 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
Is it possible to send messages in this section #1062393052863414313 so that I can describe everything in my problems in detail?
is your question related to DOTS at all?
No not related, I thought this was a regular forum section
I have deleted your post. That section is for DOTS.
Hence its name and pinned post.
So I didn't write anything there :0
Well ask your question in the appropriate channel regardless #🔎┃find-a-channel
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.
when i try to inherit from ComponentSystem it says that the namespace isn't found
any help would be greatly appreciated
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
}
}
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?
CompareTag is a Component exposed method right? which means it should let you use it directly on the Collider2D reference (other) since Collider2D inherits from Behaviour which itself inherits from Component.
Do you have any specific reason to prefer using the CompareTag method from a Transform?
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?
yes
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.
The end box is the start position + direction * hit.distance
Same logic for any cast
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?
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
Don't have to guess, I wrote a debugging library that uses the logic
good to know!
Oh, thanks!
I don't personally use CompareTag methods and use Components directly.
also isn't that what collapse does?
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
yeah! that's what I ended up doing the last time I asked this question...
sounds like a faire approach!
oh, I missed your question in there, yeah! collapse does collapse printed values, only if they have the exact same message...
but let's say a value changed, yet worse, a value that continuously change, that wouldn't count as the same message, thus won't collapse...
now your question isn't left in the void 👍
a regex based collapse implementation would be cool 🤤
It would be better if you made your own little debug ui either with IMGUI or a canvas, the console is not really the place to track a value like that
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);
}
are you destroying / disabling the object coroutine runs on
no
did you check console for errors
the gameObject is only destroyed at that last line in the coroutine
no errors
well you're switching the scene no? I dont think the rest would execute..
(the gameobject is not destroyed on load)
as I mentioned earlier, the code works like a charm initially
and you are starting coroutine within this clasS?
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
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
it's not
alr need to provide a bit more context
just guess work rn because can't see the full picture
which one is DDOL btw
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
why not:```cs
yield return SceneManager.LoadScene(1);
instead?
that's a thing?
no
I just didn't know that's a thing
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 ?
oh! I wasn't saying it is
however, it's more convenient since they're already in a coroutine...
yes
was one of the first things I did lol
do you mess with TimeScale anywhere ? would be good to know what you tried to debug this
I don't change timescale whatsoever within the scope of this
XP++
or at all ?
not just this script
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
oh ok , jus checking because that would stop it
and as I've mentioned prior, it works fine initially
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
that may be it
must be a 2022 thing since I never had an issue with that in the 2019 version
that basecode would't change between 19 and 22
time.TimeScale = 0 when the game is paused
and the player goes to the menu when the game is paused
timescale is a global setting so it wont reset if you changed it in another scene
and it never undoes that timescale change
I never had an issue with that in Unity 2019
i doubt they changed how it function but Ig anything is possible with unity.
no prob glad it worked out 🙂
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]
change it to serializefield private first
I wonder what made you suggest that...
could you elaborate please! I'm curious about knowing!!1
declare everything as public not a good idea and other scripts can change this field (probably the causes of missing reference)
error still stands
there is only one script in the whole project, the one I sent above
thanks for the explanation mate!
probably duplicate script
insert a single debug.log (Log("called") or whatever you like) or search the component in hierarchy
is this a prefab you are spawning?
not prefabs, they already exist in hierachy
only one script component exists, and it is the one under the Stadium gameobject
if it helps, even during runtime, the field values are not null in the inspector, they still show the intended gameObject values.
did you recently switch up types ?
what does that mean? I store Transforms, I use Transforms only.
what happens when you double click the error
what is entire stacktrace
the line is throwing because its the firstt time you access it
not really, I access it at Transform closestRow = Rows[0]
but it would give null if it didnt exist (if im not wrong)
i will debug.log everything, some elements are null but it seems impossible
which is why something is wrong , the list isn't null
the array is not null btw
Transform something = null is valid,
null.position is not
i see the inspector shows the array is filled
worth a try to just recreate this object and attach script again 🤷♂️
I know that this isn't a loading problem, because Debug Logging on update keeps printing the same error
Uh guys I just created the StadiumObject again, attached script and put the values in and it worked
what are u talking about?
anyone know why this happened in the first place though?
nice
unity things 🤷♂️
there are scripts create that based on composite collider 2d, you can google it
something might gone weird during compilation first time
its pretty uncommon tho tbh
when you attach script to object it creates Instance, maybe something went wrong during serialization
alright
for last version of unity editor no one of them works
sad
why would unity version change how script work 🤔
actually idk, but in older versions everything works great
How can I make a Pickup Item and Place Item System pls I describe everything in detail in the forum - https://forum.unity.com/threads/pickup-item-and-place-item-system.1530037/
You seem to have been given enough relevant and helpful info in the forum thread. Nobody is going to write code for you “just the way you want it”
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.
Well you can use two methods Vector3.Lerp for the position and Quaternion. Slerp for the rotation, you then lerp and slerp from the objects current position and rotation to the desired predefined position and rotation. You can have a script that defines the placing spot
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?
Is anyone familiar with a bug in TextMeshPro where it does this?
The text input is correct
Does it occur if you do not use the new line character?
Align left?
Yes
Are there special invisible characters between e and l?
No, and hardcoding the string makes no difference
(as opposed to getting it from a spreadsheet)
Does it occur only with level or any string beyond the fourth character?
Only with Level
Does changing the font size a bit higher or lower affect this?
Are you typing it in manually or is it filled with code?
Or just "el", really
It occurs either way
Does it do it with a default Ariel font?
Only with this font
then it's the font.
It's fine in other applications, so it's something to do with how TMP encodes it
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.
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?
Speed doesn't really matter, occurrence does. Will this object be moving in Update or Fixed Update (physics)?
sqrMagnitude is more efficient
I apply an initial rigid body force on instantiation
I thought so too, good to confirm
Obviously that's gonna return the square distance but the square of 1 is 1 so nothing changes 🙂
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
if (A=B)
btw newList and cachedRoomList are pointing same list
Might be really bad kerning. Try turning it off
Font Features, at the bottom of the "Extra Settings" section
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
Thanks. Already resolved it by regenerating the atlas with "extended ASCII" but I'll keep your solution in mind in case it comes back (because I don't really trust my solution)
Either the tile should have a reference to the piece that is ontop of it or every piece should have a reference to the tile it stands on.
How do you check if the tile is empty? Do those highlight for you?
So with the High-Fidelity URP asset apparently there is some sort of native motion blur?
Has anyone had experience with this?
when the game starts, in start function i make the chess piece child of the tile
What is High fidelity URP
Do you mean HDRP or is that a thing?
nah, the high quality URP asset
There are a few presets
it's called "High Fidelity"
You might be seeing TAA artifacting. Motion blur would have to come from a volume
My quick google didnt show anything relevant
(although, isn't anti-aliasing configured entirely on the camera, not the URP asset?)
if i share the code can you help with tha
Let me investigate
that
Then you can check if the tile has a child; if not, it's empty (unless the tile has more than one child) . . .
If you already have a way to check for when it's empty; use the same method to check for when it's occupied . . .
@heady iris It's not TAA sadly
can you get a video? (also, this should go in #archived-urp )
However, I've noticed that I can't turn off Motion blur during runtime. Even through the volume has been updated through code.
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?
How are you turning it off, show code
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?
I would imagine that the attribute is used only once, not continuously
I would not worry about it
MotionBlur motionBlur;
postProcessing.profile.TryGet<MotionBlur>(out motionBlur);
motionBlur.active = false;
``` @hexed pecan
Try motionBlur.enable.Override(false)
And remove motionBlur.active = false;
Does not have a method .enable
Sorry I was looking at the wrong thing (a parameter)
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
shall i share code?
I would, so anyone can help . . .
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 🙏
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?
cant you assign them directly in inspector?
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
hi
I have programming doubt can you help
moving objects across scene will not lose the reference to any components in its subtree, unless you are referencing objects on other tree.
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
Make sure you're in pivot mode (not center) at the top of the scene window. Not a coding question either.
Ah thanks, and sorry didnt check the correct channel
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.
SOs should be used for immutable data, not data that can be modified at runtime
Because the changes wouldn't persist unless you used the code in the editor (leads to compile errors in the build)
I belive createInstance is like making another SO from the asset menu (default values), while instantiate just duplicates that specific asset (using serialized values)
Is this just for development? Because you can't save SO's at runtime
In a build I mean
If you use new() the native part of the SO won't be set up properly
If you want to copy a template, use Instantiate
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?
Creating the instance with the SO values would be using Instantiate
Thank you! I will try
So in this way, can i use these like default classes, i mean can modify values, booleans etc. then serialize it for save to the json.
Its looks like this
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?
try to follow SOLID principle and they can help with tight coupling
esp DI part
if you need to mess with execution order of script then something might def be flawed in the structure
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?
what do you expect to happen?
it seems like being stopped in place while the block is being broken is intentional?
I do want it to stop
the issue is that in second 3 the player is able to go through the blocks when it moves a lot
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
correct
Oh, so the problem could be that I'm using Transform.Translate to move the floor?
I'm using OnTriggerEnter and OnTriggerExit to handle the block collision with the player
it could, yeah - moving the transform is effectively "teleporting" it by a little bit each frame, there's no physics interpolation checks happening to stop colliders moving inside each other if done that way
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
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?
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.
yes
Custom Method/Asset handler
||
AssetBundles/Addressables
hey everyone im losing my mind trying to figure out unity actions i tried to look at the docs but this sample code doesnt work https://docs.unity3d.com/ScriptReference/Events.UnityAction.html because you cant add MethodGroup to UnityAction or something
Share the code that doesn't work.
UnityAction is basically the same as Action. They work identically.
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
It should work. Is that actually your code?
Share the code from your script file. Not the example.
i copied the exact code and it game me the errors
That's not possible. Take a screenshot of your console window.
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
Unity just made their own (wrapper) versions of Action and Events . . .
Right. Hmm UnityEvent makes sense cause the inspector advantage, Unity action kinda just sits there lol
true. i bet they didn't want to break cohesion if they used System.Action . . .
unity events are awesome. i've grown into them . . .
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
When you have to work with designers 
Best to ask in the #1062393052863414313 channel
oops sorry about that tysm
You should, when using them appropriately they can save a ton of time and make it a lot easier to adjust projects as you go
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)
var job = new FindPathJob
{
startPosition = something,
endPosition = something
};
JobHandle pathFindJobHandle = job.Schedule();
Then later on in the frame when you need the result you do pathFindJobHandle.Complete();
i usually write on this way
JobHandle handle=new FindPathJob(){initializations}.Schedule();
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
You would have to press the E key the exact same frame you entered the trigger. The architecture I like to use for this is case consists of raising a flag(a bool variable) OnTriggerEnter and setting it to false OnExit, then in Update I check if the bool is true and I have pressed the key
im sorry im still learning could you explain in a different way. i dont think i fully understand
so create a bool in OnTriggerEnter
then in OnExit set it to false
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)
ah right so, what ur sayinf is this is working but exclusively for the first frame
and in update i check if the button is pressed and check if the bool is true
yes
and i guess i replace && Input.GetKeyDown(KeyCode.E)) with && bool = true?
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
Yes but you will have to define the bool in the class not the OnEnter function
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?
yes, since on trigger enter only fire once, if player press e after he enters the collider the method will miss
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
the bool should be renamed to eg playerentered, then check it in update
ok
how do i check it in update exactly?
if(playerEntered&&e key down)
ah so here i put in that if statement bool playerentered = true;
read what uri have said
ok
im still very confused.
also i tried renaming the bool and this is what i got
show the screenshot, where you put the bool
i realized i was in the wrong spot outiside the public class DialogueTrigger : Monobehavior
@fervent furnace so here do i set it to true outside of the if statement?
yes, but you have to check if the collider is player
playerEntered=collision.comparetag("player");
so if (playerEntered=collision.comparetage("player");
{
playerEntered=true;
}
like that?
comparetag already returned a bool, dont need the if anymore (though it is still valid syntax)
ah
and this is its own thing in ontrigger enter?
only thing? yes
left the checking (and getkeydown) in update.....dont do it in OnTriggerEnter
so get rid of the && Input.GetKeyDown?
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
where is the update
and TriggerDialogue will be called right after the player enter the collider
finally !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
- detect if player enters the area then set the bool to true in triggerenter, reset it in exit
- check if player enters the area by that bool (setted in ontriggerXX) and check if player presses e in update
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?
private void OnTriggerEnter2D (Collider2D collision){
playerEntered = collision.CompareTag("Player");
TriggerDialogue();<----
}
and the update is empty
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
yes, and you didnt check anything to fire TriggerDialogue()
where/how do i do that?
update
right so if(playerEntered=true && GetKeyDown(Key.code E))
{
TriggerDialogue()
}
?
something like that?
yes
what is wrong with my syntax here for these two erroras
like clearly im doing something wrong
) in wrong place
not stupid, careless which is even worse
ouch but true
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.
If that's a prefab it's not a prefab instance
Wrong thing entirely
oh it has to be prefabInstance and not GameObject?
Typically EditorUtility.SetDirty or asset database.save etc
No
Prefab instances are the copiea of prefabs in a scene
ooooh
This is the original prefab
It's not a prefab instance
So some function that deals with prefab instances is inappropriate
okay then replacing "PrefabUtility.RecordPrefabInstancePropertyModifications(saveablePrefabs[i]);" with "EditorUtility.SetDirty(saveObject);" is correct?
Well I'd do it on the SaveObject component itself
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
Your DrawRay is using a different position than the Raycast
Raycast is using transform.position
DrawRay is using _ladderClimbingRaycastPoint
You probably meant to use _ladderClimbingRaycastPoint for your Raycast
oh im dumb, ty
forgot to check if i changed all before testing
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
"scales up" ?
You mean, they spawn to fast?
yeah a lot
Haven't you written your code this way?
------------------------------------------------------------------------------------------- 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
Please, code!
ofc you need to wait then instantiate, not spawn the object then wait and do nothing
the difficulty is more tame now
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
what does WaitForSeconds in the end of the method bring you?
not sure, just what people use in IEnumerator
only way ive seen to wait and it actually works
Ok, please, break it down to me.
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
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();
}
}
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
// code goes here
Why wouldn't it?
But that does look cleaner
what does?
oh nvm, and the code would look a little cleaner if i can implement that
also it would work.
nothing hard to implement
I want to spawn independently of anything
Yes, I've provided you with a snippet that does it, if I got you correctly
ok will try that out thanks
feel free to ask additional question about this issue.
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
Why one? What makes you unable to serialize more?
that's what im wondering as well
my serialized list has 2 events
but when I initialize the dictionary that list is only of length 1 ?
Those events are values, right? What makes it hard for you to add one more value? Doesn't the + button under the Value field work?
What does the “initializeDictionary” method do?
private Dictionary<TKey, TValue> InitializeDictionary()
{
return _contents.ToDictionary(keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value);
}
It doesn't affect the Inspector.
The count 2 would be inside the value no?
thats what i'd expect.
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
Check the contents of the value in the debugger then.
that's what i posted here
Its not unfolded
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
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)
you are telling it to spawn 10 times
also i have the coroutine in the update function
So spawning 10 times every update call? (With the first time delayed, then every frame after)
lol yeah
And your surprised you get more than 1?
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?
Doing ANYTHING "decreases performance"
All code will halt the main thread for some time
So there is no reasonable answer to your question without knowing more.
Other than saying profile it
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
Why would 18 be 0?
0 should be 0, and 24 should be 1, right?
ik but its too late to change that i have about 10 gradients and animation curves set up for this
but why doesnt the function return 0 ?
Because you are converting 24 to a 0,1 value....
And 18 is not 0 using that math...
it is
1 - (1/24 * 18 + 0.25) = 0
1 - (0.75 + 0.25) = 0
I know I dont have to say it twice but I am quite desperate at this moment
Compiler don't lie.
Maybe time is the not the value you think it is
then why does the debug log tell me that it is 18 right before it is being used
i fixed it by changing it to 1/24.0f
Ah yea, int division vs float division
I am really desperate over this, It's a bit urgent
sorry
I haven't looked over the code yet but is the rotation and movement coupled within the same class? That might cause all sorts of issues when they're not modularily implemented
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
the answer will always be "ofc there is a way"
there are usually more than a way
just use an int
or float
then convert it to a time
What about when we have total of five games in one app, and I want to record the time they spent on one game?
I also have login and registration
what about it
Is there a code or something, that I can search on for tutorials?
what's the issue? if you already have login with firebase, keep track of those values in firestore
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
I'm using realtime database, would it be possible with it or should I use firestore instead?
Unfortunately, my team already worked on other parts of our game using firebase, wish I've known that
rip
sure you can
Okay! Thank u to the both of yall!
New to custom inspectors, is there a editorguilayout method for tilemaps? Kind of like how EditorGUILayout.Toggle is for booleans, I need something for a tilemap. I looked through some of the methods in this link but not sure what to look for: https://docs.unity3d.com/ScriptReference/EditorGUILayout.html
assuming it's a serialized property, usually you'd use PropertyField
Serialized property as in the original tilemap variable with the reference shows in the inspector?
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
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)
Repeated WaitForSeconds is not going to give you an accurate timer
You'll need to use your own float timer and Time.deltaTime
And yield return null
could you give an example?
Not really because I'm on my phone
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
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?
#🏃┃animation would prolly be more suitable for this kind of question
thx will post there
how would i do momentum/acceleration for a rigidbody
AddForce
its physics they already have momentum
just need to use the correct method to move (the one mentioned above)
what about slope momentum, would it just be adding force on the slope direction
well yeah
it will go up the slope but slow you down
yeah
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
Either make the Start async as well or wait in update/coroutine another async method before displaying them in the game.
I made start async but I still have the same issue
whats in your start()?
`
async Start(){
Debug.Log(scores);
}
`
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?
I mean you'd have to actually wait in here or there was no point in making it async
oh that works now thank you
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
right that makes sense, i wanted to add the async calls to be in awake because I wanted the leaderboard to show when the scene loaded
awake should be used for local init, start should be used for actually doing stuff
oh ok i got that confused thanks
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.
Use the debugger and breakpoints to see why it is hanging. I assume your code doesnt mark a point as checked/visited already so it is just constantly checking between the same set of points no matter how few you have
sounds like a pretty standard A* graph situation
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
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.
IEnumerator activeCoroutine;
activeCoroutine = StartCoroutine(Test());
StopCoroutine(activeCoroutine());
How do I convert type coroutine activeCoroutine to IEnumerator to achieve the above mentioned code?
Something has to be looping or recursively going through your nodes, otherwise you dont have a graph algorithm
*infinite loop
The coroutine is stored in that variable, you dont do () on it. That's all
And its type Coroutine
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html
Docs tell you exactly how as well
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
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.
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
that sounds like the signs of an infinite loop, but I don't see one directly in this code. What about code that interacts with this?
You just said it was freezing in playmode:
playmode wont load and i have to close out unity through the task manager
Yes, that looks like an infinite loop
it looks this way when the infinite loop happens in the first frame of the game
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.
have you tried reinstalling unity
That seems really extreme so clearly no.
restarting your computer?
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
Delete the Library folder while unity is closed. Reopen.
It will take some time to regenerate the cache
And yes, this is an error from unity itself. Whenever you see UnityEditor at the bigging of the stack trace, you know it
So just literally delete this entire folder and that won't have any negative consequences?
Correct.
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
Am curious why it does this to begin with
Dunno 🤷♂️
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;
}
i usually prefer to create a different data type,
1 so i can only save needed information, and
2 because if you rename the field here it doesnt mess with the save system at all
Yes, I agree
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
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?
About renaming, I use key ids instead of field name. So, renaming would be OK
ah then it probably doesnt matter much. though it might be nicer to read with a different type so there isnt too much fluff in the main code
this alone doesnt really make much sense. You havent really described what this is for, so at the end of the day this is just a class (that cannot be created externally) with a bunch of strings. Id say everything being strings sounds like a problem, but idk what these are really for
2 things
- Random int the max is exclusive

