#archived-code-general
1 messages · Page 282 of 1
can you explain more? do I do that using events?
that's what I do currently for that type of situation
yeah, pretty much using events. Update damage, and everything that's subscribed to that property should recalculate and apply it to that ability.
WoW had snapshotting for the longest, and there were cases where you pop all your ability increases (that lasted for like 5 seconds) and people found ways to keep lingering effects ongoing forever.
PoE had snapshotting long ago, specifically used for summoning
It still does but only for some things, because that gameplay is fun (but not something they wanted everyone to have to deal with always)
yep, yep, it's a common thing - first you use snapshotting, then you try to get away from it 😄
whynotboth
so i could have a "mutliplier" on each damage effect that would take a percentage of the player damage
so if I want an ability to do 90% base damage i could set it to 90
What I've done is pick out a few modifiers, flat, percentage, and additional percentage. All abilities have their own internal modifiers, but when you apply other sources you'd just append to that ability's modifiers but keep track of them in a list
then force a recalc of that ability specifically to cache
so loop through each list and apply it in whatever order, ie inc% first then more%. Do you think these "internal modifiers" should be on the ability itself or the DamageEffect
since not every ability would even do damage or anything related to increased percentages
flat -> percentage -> additional percentage
yes
if an ability shouldnt do damage then don't flag it as having damage, so it wont subscribe to damage
so have these events subscribe on the ability SO itself?
then if it's a damaging ability, it passes that damage to the DamageEffect?
right, each ability will subscribe to your modifier handler
yeah, craft it internally, but have tags on it still to tell it what extra modifiers (from your handler) it can subscribe to
enum as the tags?
enum flags
it's quick enum comparison
for when you have tons of flags
better known as bitwise enum (probably have used them for layer masks)
a "flags" enum has values of 1, 2, 4, 8, 16, ...
so I can use logical operations on them?
you can turn on or off 32 different bits
this is very performant when compared to, say, a list of IDs
is there a way to check if I'm leaking things from UnityEngine.Pool object pool?
good for adding those fluff tags like FIRE damage increases. Grouping modifiers by these fluff tags would require some more setup, such that you aren't just comparing by stat tags, but an additional fluff tag comparison operation for all modifier objects (for that specific stat)
just seeing the number of objects that have been allocated would be sufficient
if the number goes up forever, i'm forgetting to return something
https://docs.unity3d.com/ScriptReference/Pool.ObjectPool_1.CountAll.html should be able to use this
The ability itself only really needs a static value for stuff like damage, as I don't see much of a reason to add %modifiers there, but that's up to how you want to do it. PoE does do some extra internal modifiers depending on abilities, but those usually have some requirements to it (close range bonus).
ah, i just realized my problem
GenericPool doesn't actually derive ObjectPool. It has an internal ObjectPool<T> in it
i'm going to copy-paste this thing and expose the object pool
do you still have to pass in a create function? if so you could have a counter that increments in there
nah, GenericPool just uses () => new T() as the create function
but all I need to do is make CoolerGenericPool that exposes what I need
any reason to not just define the create yourself in ObjectPool<T>
assume it was designed for Go's but well it does not care how you create things and lets you provide the function for that
I need to make functionality for a radar in unity, what are some ways I can get references to objects within a chosen range of the player? I was thinking of something like getting a reference to all objects with a certain layer in the scene, then check if they are in a within a certain distance from the player (by using distance formula or sumn), then transfer that information to a 2D plane for displaying on a map.
I feel one issue with that idea is I would constantly have references to everything in the specified layer
Which may cause performance issues
I need to make functionality for a radar in unity, what are some ways I can get references to objects within a chosen range of the player?
Physics.OverlapSphere
Oh, that might work, but I need a way to not account for the y axis.
OverlapCapsule is simpler actually
basically you just do a really tall capsule with the chosen radius
tall enough to cover all possible y positions
I have an odd coding / unity question. Is there any way for me to hold a list of prefabs in a scriptable object? I continue to get Type Mismatch in the field instead of the actual prefab itself
Yes a regular List will work
List<WhateverType>
Hey all im following a brackeys tutorial and ive gotten to a part where he explains that we want our character to look the way we are travelling but mine seems to be walking sideways lol.
as long as WhateverType is a script you have on all the prefabs, or is GameObject itself.
Sure, i guess ill have to try a list itself instead of an array
which side of the thing did you put your eyes on?
List or array will work
either one
it still gave Type mismatch hm
i had just stuck em on on facing the z axis
Share the code🤷♂️
Show screenshots and show the code
show code
its nothing special lol. I just have a test array for now, and my prefab is a game object with the script CapturePoint on it
show the full script
yup sure
your Atan2 call is wrong
it's y, x. Double check that against brackeys
sure but there isn't anything in here that should cause something like that
The whole script means including the usings
This might
how about capturePoints = FindObjectsOfType<CapturePoint>();
there aren't any usings beyond the normal ones
i can try but that isn't being called in the editor
and when you drag it, it immediately says type mismatch?
yes
try restarting Unity
Also just to make sure - CapturePoint is a MonoBehaviour class?
His actually says X,Z but i was playing around with it too see if thats whats wrong (x,z also doesnt work)
z, x would be correct
at its base its a monobehavior. Its CapturePoint : Objective -> Objective : MonoB
I have an issue where OverlapCapsuleNonAlloc makes me need to select a single layer via the index int value, but I might need multiple layers.
it doesn't make you select a layer index
that's a layer mask parameter
you give it a LayerMask
public LayerMask myMask;```
He goes right and left fine now but he looks backwards when going forwards and forwards when going backwards
LayerMask converts implicitly to int
Trust me, pass a layermask in
Restart sadly didnt change anything
it returns an int
(the number of colliders it found)
not a bool
you can't do if (int)
only if(bool)
oh, sorry.
also, unity is saying there is no reference to the object in the Log method. Here is my code currently: ```cs
private void Update()
{
Physics.OverlapCapsuleNonAlloc(transform.position - scannerVertical, transform.position + scannerVertical, scannerRange, results, layerMask);
Debug.Log(results.Length);
}```
oh wait, its because the results variable isnt being assigned isnt it, its just kinda there because I have the overlap logic, but it isnt doing anything.
Would it be better for me to use the normal OverlapCapsule instead?
Take a screenshot of the CapturePoint prefab.
Just to make sure, you're not dragging in objects from the scene hierarchy, do you?
i think you're just using the nonalloc version wrong? results.Length doesn't give you the number of results, it gives you the size of your results buffer, so if you don't check the return value you don't know how many items there are in it
i think i figured it out. I didnt realize you couldn't assign stuff in a scene.
it works if i use the prefab from my project
Yes, things outside of the scene can't reference things inside of the scene, as they don't exist(outside of the scene)
which is unfortunate, beacuse i want the versions of the prefabs in the scene
yeah so i dont think there is an answer i haven't already solved
will just need to write in a new thing in the level to have a scene name to load when its selected
What is the perk of using NonAlloc instead of the other one?
the fact that it is not allocating
If I need to access the positions of objects in a overlap capsule, would it be better to use the normal one?
why? the non alloc method provides that information too
always non-alloc :)
How would I use the nonalloc method similar to how I'm doing this? cs private void Update() { Collider[] scanned = Physics.OverlapCapsule(player.transform.position - scannerVertical, transform.position + scannerVertical, scannerRange, layerMask); foreach (Collider i in scanned) { // Create icon on scanner screen // Move icon to current position // Delete icons that are nolonger there. } }
you pre-allocate an array to store results in
the method tells you how many items it actually found
it's not reassigning the array (that's impossible)
I'm sorry, I'm a little lost. Please explain.
private Collider[] overlapResults;
void Awake() {
overlapResults = new Collider[16];
}
void Update() {
int hits = Physics.OverlapCapsuleNonAlloc(player.transform.position - scannerVertical, transform.position + scannerVertical, scannerRange, overlapResults, layerMask);
for (int i = 0; i < hits; ++i) {
Debug.Log($"Hit #{i}: {hits[i]}");
}
}
https://docs.unity3d.com/ScriptReference/Physics.OverlapCapsuleNonAlloc.html
If you get 16 hits, you don't know if there were actually 16 things in the area, or if there were more than 16 and you ran out of space in the buffer
Before everything else, do you understand what a memory allocation is?
Setting away space for data
to save for later
notice how Physics.OverlapCapsule returns a Collider[]
this means that it has to allocate a new array each time you run it
Yes
you probably then use the array once and throw it out
so it gets garbage-collected later
Well, it's not wrong, but you're missing the point.
Memory allocation is when you tell the system(or the app, depending on stuff), that this address in memory is gonna be occupied by something. It involves checking if it's not occupied already and notifying stuff to not occupy it later. In C# reference types are allocated on the heap and are subject to GC(garbage collector), so it also involves some logic with the GC, like keeping track of the referencing objects and stuff. That's why memory allocation in C# is relatively expensive. So instead of allocating stuff every update, you would do it once in awake for example and keep on using the same allocated object, just overwriting it's fields.
Normal Overlap method creates a new array under the hood which is a memory allocation. Non alloc version, fills the array that you pass in instead, so it doesn't allocate anything.
Garbage collection is a non-trivial cost and can cause some very nasty hangs if it takes too long.
That's why the profiler has a "GC Alloc" column.
that shows you how much heap memory your code is asking for each frame
That's true, but there's also a tendency to exaggerate it's costs. If you allocate just a few bytes every frame, it's not critical. Any kind of optimization should come from profiling and identifying a problem first.
While caching might seem like a perfect solution with no downsides, it's not. It makes your app consume memory. If you rarely ever use all the preached space, your app just uses more memory for no reason.
indeed
Then you get games that require 32GB RAM for no particular reason
Ohhhh, I had no idea that that was how memory worked in C#, thank you, that is incredibly useful information. That explains a lot.
That all makes much more sense
one easy way to reduce that cost is to just make that array static
you're not multi-threading, so it's impossible for two methods to try to use the array simultaneously
now you've got one array that every single instance of your method re-uses
ok so like
how would i get RenderSettings to serialize in a json
its a type, so it wont work
We barely just scrapped the surface of memory management in C#. There's a lot more to it. I suggest checking the C# manual at some point, as it covers it properly.
well anything i can do to get it at least kinda working
I presume you want an instance of RenderSettings
yeah
How do I make it so that in my VR game, when I pick up a book, how do I make it open automatically to just one page? I'm not gonna end up having multiple so just the one.
do you have a book already with page separated?
or are you doing UI for the page
Rn I don't, but I do plan on modelling my own with the pages being their own separate objects.
physical object you can grab
this would mostly just be animation work then
how do I make it open automatically to just one page
animate the book opening!
i'm unclear what the problem is
ah alr. Would it need any coding like lets say, I code it to so like if book is grabbed, then open page
something like that
you can probably do it all with the animator
For making a radar (technically a minimap), would it be bad to clear something made last frame and make a new version of it at a different position?
I have this: cs private void Update() { int hits = Physics.OverlapCapsuleNonAlloc(player.transform.position - scannerVertical, player.transform.position + scannerVertical, scannerRange, results, layerMask); for (int i = 0; i < hits; i++) { Debug.Log($"Hit #{i}"); } foreach (Collider i in results) { // Clear and Create icon on scanner screen // Move icon to current position CreateAndClear(i.transform.position); } }
Destroying and instantiating icons every single frame will be producing a lot of garbage
But it's a perfectly valid place to start
We're not sure what you mean by "clear and create" too. Are you actually referring to instantiating?
Yes
I was planning on deleting all of the icons, then creating new ones at the new positions. I was also thinking it would be messy.
Start with that and see if it causes any issues(profile the method for example and see how much GC it allocates). Then make a decision wether you need to optimize it or not.
A pool of icons might be a better approach, but it's up to you to decide wether it's worth the effort or not.
Why are you trying to serialize a type? What's the goal?
Would using a for loop be the best way to destroy the icons? Since they are child gameobjects of the plane this script is attached to.
rendersettings is different
its pretty much just the environment tab in lighting settings
it even updates properties depending on current scene
i wanna serialize it and store it in a json so i can load it externally later
okay, but you don't want to serialize a type
the problem is that all of its properties are static
i mean serialize the data in it
the data is never gonna be modified after its saved, so i just need the data
You can instruct it to serialize something's static fields
ah, and you're using Json.NET, so there you go
I'm not so sure about deserialization
What other options do you have?
I can't think of any, but I am experiencing a problem
Is it unity type? Or your own?
Currently I am getting an error saying at line 43: "Object reference not set to an instance of an object". Here is my script: https://hastebin.com/share/ilitizuqol.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
unity
Share the entire script.
The line numbers are off because you excluded the using directives
Ok, then you definitely shouldn't try to serialize it.
i meant the data in it
If you need to save the data in it, store it in an instance of your own type.
i tried that and it just wouldn't work
idk why
you will need to copy the data you need out of it
Oop, sorry, here: https://hastebin.com/share/egadosibaf.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
just would always error about smth
Wdym? What errors exactly?
there's no reason you can't just make your own class to hold the data and serialize it
i remember one was just a "null reference exception" like nothing else just that
Your foreach loop is wrong
another was smth with json encoding, it seems to freak out abt colors
OverlapCapsuleNonAlloc returns the number of hits
It doesn't change the length of the array (that would be impossible)
You need to use a for loop to iterate over the valid indices.
This is a very simple error. You should be able to solve it if you're asking in this channel.
A foreach loop will give you every item in the array, including items that were never assigned to by OverlapCapsuleNonAlloc
Share the error details.
i deleted the script with the intent of starting from scratch
as it was already becoming too much of a problem
then i asked here
Well, you can't serialize a type and definitely not one that unity didn't intend to be serialized.
well, we can't tell you very much if you deleted everything
actually hold up
i think i still have the script
found it
thats the class i made
So I would put the CreateAndClear method in the for loop and get rid of the foreach loop? How would I plug the Colliders into CreateAndClear()?
Yes.
for the exporting, literally just created a new entry in the json export using new DimensionRenderSettingsObject() since CopySettings() wouldn't work
If the overlap finds 5 items, it will only write 5 items into the array
You must not try to do anything with the rest of the array.
Please share the code correctly!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.
do not derive DimensionRenderSettingsObject from UnityEngine.Object
just make it a plain old class
don't derive DimensionRGBColor from it either
ight did that
still cant copy over the data due to due this???
cant figure it out
How?
by writing a for loop that only iterates over the valid indices
Look at what my script does.
whats the difference between ++i and i++?
nothing in this case
oh
I just use prefix by force of habit
sorry
Share the line that is underlined
OH
The overlap method stores each collider it hits into the array. That's all it does.
I GET IT
So if it doesn't fill the array, you have random trash left in it
SceneRenderSettings = DimensionRenderSettings.CopySettings(),
Does anyone have a key door system
So I would do CreateAndClear but instead of i in the perenthesis I would do results[i]?
CopySettings is not a static method, yet you try to use it as one.
Yes.
Likely many people do.
What have you tried and what are you struggling with?
In essence you just enable a bool or store a value and check it when you are near a door. So learning about trigger colliders should be enough to get it working
That makes so much sense
Thank you so much!
Ill work more on that tomorrow. I got to go to bed I have exams.
YES OMG I GOT IT WORKING
thx
ok rq
any way to have the SceneRenderSettings table entry be conditional-based, currently doesn't export if there's no external lightingsettings and i wanna fix that
code:
bool hasLightingSettings = descriptor.SceneLightingSettings != null;
var dimensionDescriptor = new
{
Name = descriptor.Name,
Author = descriptor.Author,
Description = descriptor.Description,
SpawnPoint = descriptor.SpawnPosition.name,
TerminalPoint = descriptor.TerminalPosition.name,
SceneLightingSettings = descriptor.SceneLightingSettings,
SceneRenderSettings = DimensionRenderSettings.CopySettings(),
Addons = new
{
SlipperyObjects = descriptor.Addons.SlipperyObjects.Select(go => go.name).ToList(),
ExtraTerminals = descriptor.Addons.ExtraTerminals.Select(go => go.name).ToList(),
TriggerEvents = triggerEventsData
}
};
basically, table has entry if true, isn't true, entry isn't there
i have a workaround, but i wanna know if theres a more elegant solution
Serialized data has to have a predefined structure. You can't add/remove stuff from it dynamically. Unless it's elements of an array or something.
You could have 2 separate classes for with and without lighting data. Or just make the lighting data uninitialized and use some kind of bool to store it's state.
i mean the dimensionDescriptor, i wanna have it export different depending on if this is empty or not
Then make a check. If it's null serialize DataWithoutLighting. If it is not, serialize DataWithLighting.
yeah i know i can just export two different tables in one if statement
i just wanna know if i can essentially have an if statement in the table, so i dont need to do that
Or serialize DataWithLighting, but a bool hasLightingData inside to determine whether to serialize/deserialize that part.
What tables are you talking about? This is not a carpentry discord.
dimensionDescriptor
its a table if im right
Just kidding. But the use of tables is not appropriate here as you serialize objects.
It's not.
oh wait is it an array
What's the type?
Ah, I see
It's an anonymous type
In either case, it's an object, not a table.
oh
But to answer your question, no you can't use a bool inside, as it's basically an initialization of the object.
oh ight
You'll need an explicit type if you want to add some logic like if statements
would it be possible to generate a plane only when interacting on an item? or is it better to put planes but invisible on every item? but the problem is, the plane should be in a different layer mask, not sure if i could do that on non physical coded planes
I want to make something like this, maybe not planes
I was thinking if it is possible to make them appear or generate only when interacting, (no physical mesh), or would not possible, and I just have to put them on every clutch/lever for the car?
how to use collider variable outside oncollision enter?
Wdym by "no physical mesh"?
in coded form like .plane or something similar (dont know the exact variable)
like how we can make invisible non physical circles for groundcheck and set the radius
You could issue a command buffer draw call, but I don't think it's gonna be worth the effort. Much simpler if you have it in the scene on a singleton or something and just enabled and position it correctly when needed
ah okok, by singleton, is like the interactor in the main camera? from how i understand, it stores the mesh but will only move the mesh thingy to the item?
By singleton I just mean that you have one of these objects in the scene and reuse it for any scenario that you need.
Singleton pattern might make it easier to access it, but it's not necessary.
- Pls atleast keep your code indented before posting
- collider is a local variable from oncollisionenter so it won't be available to use outside of that scope.
You can store its value by creating a global variable to use it from other functions

Holy moly. I didn't notice that.😱
I feel like the ide should automatically fix that? I am so used to my linter though, not sure what is there by default
Clippy ❤️
It should be fixing that by default. I'm not sure why it doesn't for them. Maybe they don't ever use Tab to autocomplete
I'm currently building a turn based game. 2 Teams, Player and Enemy. Player is controlled by the user, Enemy is controlled by algorithm.
There are several characters per team. The order in which they have their turn is based on each characters "initiative" value (similar to games like HoMM, BG, DoS, etc.).
My current approach: in instantiation, create an array of all Characters and order this array based on the initiative value. The turns cycle through each element of the array and then starting back at 0 again.
I feel like this approach might limit me in the future (spawning new enemies during runtime, removing enemies, etc.). Any ideas how to implement this more solidly?
havent played HoMM BG DoS before.......
but i guess you mean the game cycle is based on some value on character not player->enemy->player->enemy....?
how often does a characters initiative value change
Initiative values are static and determined before scene launch.
@fervent furnace yes exactly.
i wonder what if
eg a turn of character with value 10 just passed but a new character with value 8 is inserted? (assume the turn started from less value first)
ie a new character with smaller value is inserted after a turn of character with higher value just passed
then I think I would just use a linked list of characters, that will be easy and quick to change should you need to at run time
@knotty sun You mean "LinkedList<T> Class"? What's the difference to a regular List for my project? Looks promising!
I mean,even a regular list would work
@fervent furnace Either re-calculate the list or only have new characters in the next cycle (after all other characters had their turn once)
You can just insert new characters into the list in the right place
Not quite, I would implement it myself. But yes, this will work for you. The benefit is it allows you to read the List in a specific order and maintain that order in an organised way
linked list itself is useless, never see the real use case of "regular" linked list (tree or graph or open hash table uses linked list but they not just a linked list), unless you have a additional hash map for random O(1) access and double linked list for O(1) remove/add
btw list will works, but i wonder who can take action after insertion? the next character right after the higher value's one or the new inserted character or or restart the game loop or other strategy? you may need an additional pointer to next character right after the higher value's one, not just insert
Thanks for the insights everyone. I will implement a List and see if it works well for me.
@fervent furnace Interesting thought - I think having a bigger cycle where all characters go through once makes sense here. Newly instantiated characters only work in the next cycle.
Instantiating them in the same may create too many edge cases
Question: Do you envisage having duplicate initiative values or will they be unique?
@knotty sun I will have duplicate initiative values. I already created functionality that iterates through all Characters with the same Initiative value and randomly orders them in their initiative Level.
then I would suggest making your initiative a Tuple (int level, int position)
@knotty sun why? and what would level / position mean in this case?
so level is the initiative value and position is the sequence of that character within that initialive
it gives you a unique key for each character
I see thanks for your input!
What's the best approach to re-order an existing list? Say I want to move element [6] between [3] and [4] for example?
that is where linked list shine.
update [3] to point to [6] and [6] to point to [4]
job done
I just read that a linkedList is not index based. I can still access each element using listName.ElementAt(n), right?
where n is the index
yes you can, see the Extension methods in the docs
although you should never need to do that if you use that class
Maybe start with a regular list. I wouldn't use linked list unless it was justified performance wise.
And it rarely is.
Guess I will try both approaches and play around a bit. It's just for learning purposes anyway.
using a regular list, what would you recommend for my question?
What's the best approach to re-order an existing list? Say I want to move element [6] between [3] and [4] for example?
clearing and re-populating maybe?
List has Remove/Add/Insert methods and many more. I suggest looking up the documentation for all the available API.
Actually feels like link list could be nice for this case, with an index based data structure like list where you keep track of the current character via index, inserting a new character prior to the index means you also have to manually shift the index by one to keep it in the proper location, and same for removal. It wouldn't be a problem for linked list since you are always traversing by next pointer than by index.
Would List
var store = listName[6|
listName.RemoveAt(6)
listName.Insert(4, store)
not work in my case?
is there anyone that could help me with my problem when i press E or mouse0 on the weapon i want to pick up it just goes invisble when its picked up and it still shoots and stuff
Sounds like an issue for #💻┃code-beginner
You mean initial index 4 is then 5, 5 is then 6 and so on?
If you insert before 4, yes.
If you share your issue details and code properly.
yeah i could screen share if you got time
but i am gonna be muted
but i will hear you
@cosmic rain
Hello. I hope this problem includes to this channel. I have TextMeshPro on canvas and I change text in runtime. That's not a problem, but how to make some letter/words bigger/thicker than others when the words (sentence) are created by one textMeshPro object? I tried applying bold to words by $, but I need make it more visible
No screen sharing. I've replied in beginner code.
@sudden portal i am in school
ok will do
Tmp supports rich text tags:
https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/manual/RichText.html
Oh. I see. Thank you!
Share !code properly
📃 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.
do you want everything
boi
like that?
lmao all good
The relevant code. Responsible for equipping the weapon.
i wrote new code below where i put the new code
ive got a stomach feeling its doesnt have anything to do with the code since ive got no errors or warnings
all my fellas, i'm trying to have my player transition to a location which i have designated with an empty game object so it's easy to adjust the position. in the player script, i'd like to do something like
//Player controller script
if (player click triggerobject)
{
Trigger();
}
if (enterPosition != null)
playerTransform.position = enterPosition.position;
enterPosition is a Transform which i would like to update whenever a new trigger object is interacted with. i have an abstract class script set up, and i'd like to update what should be saved to enterPosition from the override method, but i'm scratching my head at how to do that.
//Door trigger script
public override void Trigger()
{
playerControl.enterPosition = doorEnterPos;
}
i've tried a few variations of this, but haven't gotten it to work yet
Don't have much time now, but logic bugs are rarely accompanied by errors and warnings.
not to rush you but if you could just take 4 min to hop in a screen share in a call so i can show you my problem
If I don't have time to look at the code, I definitely don't have time for a screen share.
just taking a glance at your issue @molten timber , i'm wondering if it might be this little part here
if (leftoverQuantity > 0 && openSlot)
{
openSlot.setItem(itemToAdd);
itemToAdd.currentQuantity = leftoverQuantity;
itemToAdd.gameObject.SetActive(false); //specifically this part
}
that itemToAdd.gameObject.SetActive(false); line might be why it's invisible: it's being set to inactive
I don't see any code related to equipping the gun... I assume it's in the WeaponManager..?
Hi, I wark with UnityWebRequest and I always get this error
{"message":"Validation failed: deviceId must be a string, adaptyId must be a string","error":"Bad Request","statusCode":400}
Cysharp.Threading.Tasks.UnityAsyncExtensions+UnityWebRequestAsyncOperationAwaiter.GetResult () (at
String that used as body in request on first screen
you likely dont want that playerControl.enterPosition to be so public, but what doesnt specifically work? You should show the actual code instead of pseudo code because what youve posted doesnt really make sense, you are calling Trigger() in a player controller script which is unrelated to your door trigger script
I would do something like, click on the object, try to get a component or check its layer which indicates this is something that you may enter. Then within the player controller script, assign enterPosition (which shouldnt be named Position)
does anyone have an elegant solution to auto tiling?
so all i gotta do is make it true?
You probably don't want to make it false to begin with
hahah
Your question revolves around an endpoint that is not related to your code
If you are certain the error is not the case, I can only assume the endpoint does something wrong
i dont understand when i add an layer to an weapon or something random i goes invisble from my game
can someone help me with that please
Perhaps you supplied the parameters incorrect?
via postman this is works correct
Perhaps log the body created in the request and validate it is valid json + the actual body you expect
Maybe that Parse method that is used does something wrong
i dont understand when i add an layer to an weapon or something random i goes invisble from my game
can someone help me with that please
Stop spamming the same message please
That looks fine. Maybe you can place a breakpoint before sending the request and see if the body is still correct? https://unity.huh.how/debugging/debugger
I can't think of a reason why this would be wrong. Perhaps the quoting is formatted wrong but I don't see why that would happen
Hello all,
Is there a way to detect collisions without a rigidbody? The collisions are very erratic due to it and I want to code the "physics" of them by hand. I only want the boxcollider to tell me WHEN it has collided
simple answer, no
Dang
I just want to make tiles that behave differently when you touch them
not make it so they cause weird collisions
If your geometry remains this simple you could make each box take custom bounds rather than adding a collider, and you check those instead
Keep in mind that doing this can be horrible if every single box keeps checking these things, and you should definitely have some type of blockmap that tells which box "might" collide with something
That could work. What's the standard way people do it? This surely can't be it, when you collide into a wall in platformers, you don't stutter and change direction
am I missing something obvious
Sorry, no idea. This is better suited for another channel
which one
do you happen to know the standard way this is done?
there is no such thing as 'standard' everything depends on what you are trying to achieve. As you have provided no information about your setup, what you are doing and what you are trying to achieve it is impossible to provide you with information
I'm just trying to make a tilemap where each different tile behaves differently when you touch it
collisions seem to make it like you're physically smacking the tile
and it applies a force against you
yes, imagine running into a brick wall irl
Yes but is it not possible to have a tile that detects a collision without also applying a force?
yes, they are called triggers
Oh interesting. I can see that option on my player box collider but not on the tilemap collider
does it only work with box
Hi everyone is there any videos that will help me add into my game where if the character touches a object it adds 1 to the score?
I think you will find it does
https://docs.unity3d.com/Manual/class-TilemapCollider2D.html
ohh I see it now. So will the trigger allow me to detect collisions without a rigidbody then?
because right now it seems to not work without it
no, you still need the rigidbody2d
I see alse this errors
there are 1,000's on YT
This seems to say at least one object must need a rigidbody. But it still won't remove the erratic behaviour and "trigger" removes any collision at all
I feel like I'd be better off just handwriting the collision logic
it's really simple anyway
and I wouldn't need to mess with colliders
why do i always get "type mismatch" when assigning my player attribute manager to a prefab?
My team and I have a fairly sizeable project containing mostly class lib projects that we use across all of our different games. At the moment we're just copying and pasting the entire shared lib folders into each of our games however we'd really like to centralise these shared lib folders and store them in a seperate VCS enviroment. What's the best way to go about this (i.e what should our .csproj files look like so they can be referenced by the unity project root .sln file and be built and compiled into our exe, apk etc.) How can we reference the unity engine and editor dlls in your shared librar csproj files (I've tried already inside VS but I keep getting an error saying the unity dlls are invalid or are unsupported). Also VS doesn't seem to like my project referncing .NET framework 4.7.1 which is what the current version of out unity installation uses
you can compile your shared code as a separate managed plugin, but normally it's easier to import the source files straight into the unity project and let unity compile it! for one thing, if you use it on multiple games, it's a huge headache to build different DLLs for multiple different unity versions
my preferred way to do it is to put a package manifest (https://docs.unity3d.com/Manual/upm-manifestPkg.html) in the shared module and check it out into each game's Packages folder so it shows up as an embedded package
Scene objects can't be referenced outside of the scene.
That sounds sensible. Shame there isn't a better approach for separation but this should work for our needs. Thanks
worth mentioning that if you're using a VCS that has a feature like git submodules, it works really nicely for that - you can also reference a repo by URL in the project manifest but unfortunately that only works with git iirc
We've recently migrated over to unity's built-in VCS to try and have a more unified development experience within unity (also it's easier for our artists)
that's the one that used to be plastic right? i think it'd be an "xlink" in plastic?
Does anyone has some knowledge on how to send live view from secondary camera into pop up style second window? Multi-display is not what I'm looking for
When making custom UI for my scripts is there an easy way to make a field that has a scrollbar
This only make that
And yes I know I shouldn't write a zero there was testing stuff
Slider instead of floatfield
Thank uuuuuuu
If I inherit from a UGUI monobehaviour and add some new inspector variables they do not show up, what is the easiest way to fix that?
Hey! I'm trying to make the tower in the middle of that big range collider clickable, I've had no success using OnMouseEnter (because the range collider will always block it and be the raycast target instead) and using Raycasting with ignore on the "Tower Range" layer doesn't work either, for some reason it entirely ignores the "Tower" layer and hits the "Terrain" layer (plane) for some reason
What would be the proper way of doing this, or is there anything that I tried that should work?
What does your hierarchy look like?
What are you inheriting from? Pretty sure youre not supposed to extend Unity UI classes
it probably has a custom editor, a lot of them do, so you'd need to create a subclass of its editor too
I've done this several times!
you probably just need to add a custom editor, yes
for example, I subclassed Button to allow it to target multiple graphics (instead of just one)
yes you are right - I need to extend the custom editor
using UnityEditor.UI;
using UnityEditor;
[CustomEditor(typeof(MultiGraphicButton))]
public class MultiGraphicButtonEditor : ButtonEditor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.PropertyField(serializedObject.FindProperty("targets"));
serializedObject.ApplyModifiedProperties();
}
}
Ah ok, that sounds handy. I was thinking of something else then
yeah, the UGUI classes are (reasonably) friendly to extension
I have to do it for circular hit detection - the rectangular-only is a bit rubbish!
From a scale of 1 to 10, how screwed up is this?
public class Health : MonoBehaviour
{
public int currentHealth;
public int maximumHealth;
// Start is called before the first frame update
void Start()
{
currentHealth = maximumHealth;
}
public void TakeDamage(int damageValue)
{
currentHealth -= damageValue;
if (currentHealth <= 0)
{
currentHealth = 0;
Destroy(gameObject);
if (GetComponent<DamageOwner>() != null)
{
Destroy(GetComponent<DamageOwner>().damageOwner.gameObject.GetComponent<DamageOwner>());
}
}
}
public void HealHealth(int healValue)
{
currentHealth += healValue;
if (currentHealth > maximumHealth)
currentHealth = maximumHealth;
}
}```
```cs
public class DamageOwner : MonoBehaviour
{
public GameObject damageOwner;
void DestroyScript()
{
if (damageOwner == null)
{
Destroy(this);
}
}
}```
```cs
public class DamageOnCollision : MonoBehaviour
{
public int damageAmount;
void OnCollisionStay2D (Collision2D other)
{
if (other.gameObject.GetComponent<Health>() != null)
{
other.gameObject.GetComponent<Health>().TakeDamage(damageAmount);
if (other.gameObject.GetComponent<DamageOwner>() != null)
{
other.gameObject.GetComponent<DamageOwner>().damageOwner = gameObject;
}
else
{
other.gameObject.AddComponent<DamageOwner>();
other.gameObject.GetComponent<DamageOwner>().damageOwner = gameObject;
}
}
}
}```
im making a horror game and i used the render texture and raw image to get a pixelated look. But the issue is that when i change the volume that has the post processing overrides, it does not come to the render texture? how can i fix this?(i used the URP template).
the post processing effect does not come the the pixelated look
@placid summit That bad?
You can definitely use les GetComponent - like other.gameObject.AddComponent<DamageOwner>()?.damageOwner = gameObject and cache other.gameObject. But I would use less micro components and have 1 Person Component that can always reference other smaller ones
this makes me want to die GetComponent<DamageOwner>().damageOwner.gameObject.GetComponent<DamageOwner>()
you also don't need .gameObject in anything in DamageOnCollision
and you should use intermediate variables instead of constantly calling GetComponent over and over
Does the camera that is updating your render texture have the correct layers your post processing volume is using?
Learn about TryGetComponent too
This was actually done on purpose
Why
I didn't know whether the code was going to stay or not, since this is still the prototyping phase
Why would you write the code bad intentionally
So I just wanted to write something as quickly as possible
It's pretty easy to get rid of the GetComponent hell with a variable
But it wouldn't matter if the actual code was bad, I'd just end up deleting it
So is GetComponent the only issue here?
Anyway why ask for a code review with code you haven't already cleaned up
no there's a ton of unecessary stuff
not just the GetComponents
the .gameObjects too
This is for the architecture, as in how the scripts connect with each other
The other stuff that's just bad reading could be changed, I have little experience with Unity's methods since I only studied C# (not even to a good degree, intermediate if we're really pushing it)
This would be better done with an event:
if (GetComponent<DamageOwner>() != null)
{
Destroy(GetComponent<DamageOwner>().damageOwner.gameObject.GetComponent<DamageOwner>());
}```
Hey ! Is there a way to tell if a SerializedPropertyChangedEvent is the one triggered at the initialization of a PropertyField so that I don't react to it? Apparently it is triggered when data binding happen
Any reason why?
so you don't have this weird hard dependency between the scripts
Hmm, actually that's a good point. Another thing to read up on (or just use C#'s events)
Yes I mean C# events
Does anyone really use such micro size components? - you will have to do so many GetComponent calls that are not super fast. Just have a Main player/enemy etc component and if required have cached references from within that to others.
It seems better to make a more modular system... when done right
The "slowness" of GetComponent is definitely overhyped
And I don't see the point in making 20 components then keeping a main Player/Enemy/Object one for calling stuff
i dont use the post precessing volume. i use the volume compoment built in urp
I have never seen someone come in here with a framerate issue and the reason for it was GetComponent
It's a non-issue
^
Besides, my game's going to have low poly and textures, and those are the worst for performance
ok that is good - depends of type of game of course
@soft shard
Storing combat result information in Health is probably fine too
Hey all i want a bottle of water to randomly spawn when you hit the first one but it doesnt work, im following it from a tutorial
Could work, that way I won't have to go through this hell just to keep track of who damaged who
can you see anything wrong?
But it might make it so that some objects have variables that you won't ever use
Well, assuming I was making a bigger game
Think this is fine for now
I would go for a few extra variables over the work of managing DamageOwner component.
AFAIK, the camera will only render post effects, regardless if its from the "Volume" component or Post Process components, based on layers
Hi, this I believe was meant in the general context of C#, not Unity, but I'm still curious to hear from you:
File Traversal: Traverse the directory tree, starting with the specified path. Will you
prefer a single-threaded or a multi-threaded approach? What are the tradeoffs?
Would it actually be worth it to multithread file traversal?
In situations where you don't know how many files and catalogs you'll encounted this sounds to me like asking for trouble. In addition, file traversal is IO
I can't really see there being much benefit in doing this, unless you have the most optimistic scenario where the number of threads somehow aligns with the number of folders and you don't spend a lot of time waiting for free threads. Is my reasoning wrong here?
Please Debug your code and see if the methods are triggered by using Debug.Log and checking your console for output.
Additionally place a log inside both if-statements to see if they are entered.
https://unity.huh.how/debugging/logging/how-to
Also, tag comparison should use CompareTag, as your IDE most likely is suggesting.
https://docs.unity3d.com/ScriptReference/GameObject.CompareTag.html
Anyone knows why this code DOES hit the layerMask it should be ignoring?
because despite common sense, LayerMask.NameToLayer returns a layer index, not a layer mask 😔
And is the solution 1 << LayerMask.NameToLayer ?
i think that should do it yeah
Or LayerMask.GetMask
Also your mask seems inverted
LayerMask.GetMask("Tower Range"); correct?
It doesn't ignore those layers. It's the opposite - it includes only the layers in the mask
Oh nice, okay.. that's probably my issue
Seems like that was it, still have few things to fix to be completely sure though
tyvm
How to know when a prefab is instantiated ?
Some callback that gets called when a prefab is dragged from the project into the hierarchy ?
In the editor I mean, outside play mode
They get called with [ExecuteInEditMode], but that's pretty clunky
Also they get called every single time I start and exit play mode =X
I'm looking a simple callback OnPrefabInstantiated or similar
I would try them out just because the behaviour of these instances are kinda less intuitive
for these callbacks
because I know ScriptableObjects and methods like Awake() have some funky behaviour (in the editor)
otherwise yeah, make an ExecuteInEditor script
could be its own separate component you can just tack onto stuff
It feels so ultra mega clunky
I can't believe there is no simple callback when a prefab is instantiated
Is there a way to ignore certain layer for OnMouseEnter and similar methods?
if you want more control than this i think you have to do the raycasting yourself
Do you know if something on the Ignore Raycast Layer will detect collisions?
Use IPointerEnterHandler instead and then you can use the mask on the Physics Raycaster component https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-PhysicsRaycaster.html
If you specifically want to know when something gets dragged and dropped into the hierarchy, there's this:
https://docs.unity3d.com/ScriptReference/DragAndDrop.AddDropHandler.html
Interesting, will give that a try, feel like I went away from IPointerEnterHandler for some reason, hopefully not true anymore
Btw you can use the ~ operator to invert a mask. So if you want to ignore Tower Range, you can do ~LayerMask.GetMask("TowerRange")
Or make a serialized field and assign it in the inspector if that's possible
very good to know
how would that look? i'm a bit confused by what you mean looking at the doc
do you mean a global setting or really specific to that one IPointerEnterHandler?
the Physics Raycaster component (which you should have on your camera) has a layermask in the inspector
that will be applied to the raycasts it does in order to call OnPointerEnter on things
so you can exclude objects like that
likewise for the Graphic Raycaster on your Canvas (for UI elements)
(these are also accessible via script, if needed)
ahhh in my case it's in a canvas so i'll use graphic raycast
OnMouseEnter doesn't work for UI stuff at all that's why I assumed you were talking about physics
but yeah same deal on the Graphic Raycaster
All Graphic elements also have a "Blocks Raycast" or "Raycat Target" checkbox as well
I'm probably missing something but I have the following, the green collider blocks raycasts (ipointerenter) on ui
and i've set my blocking mask to not be blocked by the "Tower Range" (green collider) layer
it's still blocking though (removing the green collider will make the pointerenterhandler trigger)
What's "the green collider"?
Is this an actual physics collider?
ye, that somehow blocks ui
yeah that'd be via the physics raycaster
exclude it on the physics raycaster
somewhat confusing but makes sense
i hope it wont break anything else
oh wow.. adding physics raycaster to my camera does break things, i'll see if i can figure out why
it seems to break some of my Physics.Raycast
shouldn't
but also the multiple raycasters disambiguate which is in "front" by distance
so distance to the camera is another lever you have here
hey thanks i will look into the action map asset, sounds interesting
oh man.. when it shouldn't but it does haha
i'll see if I can figure it out
i mean it only breaks one of my other raycasts so that's interesting
the one here
private void Broken() {
_ray = _mainCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(_ray, out _hit, 1000f, groundLayerMask)) {
if (!_toBuild.activeSelf) _toBuild.SetActive(true);
_toBuild.transform.position = _hit.point;
if (Input.GetMouseButtonDown(0)) {
// if left-click
BuildingManager m = _toBuild.GetComponentInChildren<BuildingManager>();
if (m.hasValidPlacement) {
m.SetPlacementMode(PlacementMode.FIXED);
// shift-key: chain builds
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) {
_toBuild = null; // (to avoid destruction)
_PrepareBuilding();
}
// exit build mode
else {
_buildingPrefab = null;
_toBuild = null;
}
}
}
} else if (_toBuild.activeSelf) _toBuild.SetActive(false);
}
}
is Transform.Find generally as costly as GameObject.Find and the such? so I don't use it every frame and stuff
oh but i found a neat workaround for not using ti every frame so might not matter
Its very helpful for multi device input, I would suggest a channel on YouTube called "samyam" who has a great playlist on the Input System package, the docs also have a "How do I...?" page for common uses
mind expanding on that or linking something about it?
seems inverted or something like that
oh wow, actually in my case, raycast only works OUTSIDE game view
(so lets say my pointer leaves game view, the object that should appear starts showing)
Generally, any kind of "find" operation is going to be expensive since it usually has to traverse a large list, and generates garbage doing so (same with GetComponent), it is certainly best to avoid doing those types of calls in Update/every frame, and caching your references when possible is usually a better alternative in something like Start/Awake or on an event
i have a pretty weird issue, so i have raycast code that works perfectly, but if i add a Physics Raycaster to my Camera, it stops working but ONLY when the cursor is inside game view
removing the Physics Raycaster solves the issue (but i need it)
in other words: lets say my pointer leaves game view, the object that should appear starts showing at seemingly the right place inside game view
show your raycast code
I'll cache all of my stuff in a nice dictionary so i can access it with string then!
Can you debug it and see which part is failing with the raycaster active?
Is the raycast not hitting? Is the code not running at all?
If I have a parent object and a child mesh... and I want to rotate the parent object... how can i make sure it rotates around the center of the mesh rather than (0,0)?
it's not hitting, in the code below the debug.log only shows when cursor is outside game view
but do you know if the raycast is even happening at all?
Put a log before the raycast
ohh
like maybe this whole function is inside something like:
if (!EventSystem.current.IsPointerOverGameObject())```
which would explain everything
it is
yep
makes sense
because with the physics raycaster now the event system sees the physics objects
i mean, there's an inverted if
The most elegant solution is replace this custom raycast with IPointerEnterHandler etc
ahhh
Would it be a good idea to make a seperate script under my player object for movement and then another for combat?
Yeah
oof i wish that part was my code, will see what i can do it's not too complex i think
ty!
Just was thinking. "God I wouldn't want to read this again" if I put it all in one script lol
Separation of Responsibilities is pretty powerful.
Very good for maintainability and modularity
solution was rather simple actually, just removing that condition to hide the preview when hovering ui
i can just code it myself if i ever need that
The only real issue is that you're gonna have to keep track of what each script is referencing, but if your code structure is good this is usually not a big deal and it's definitely faster to find what DealDamage.cs is referencing compared to searching for it in a huge class
If that works for your usecase thats probably fine, the downside with strings as a key though is that they can be easily mistyped or changed, if I need other scripts to access references, I usually make a public property for them and pass a private cached variable, though if the dictionary is private (as in other classes dont need access to it), you probably could just have the references without a key-value
i dont get what the private cached variable and the references without a key-value parts really mean.. but I get the typo part! And letting other scripts access my dictionary may be a bit tricky
I would start with things that could be used by AI objects. I generally separate "Player" stuff from functionality of the object.
If other scripts dont need to access your dictionary, then I dont think you would need a dictionary, you can just store the references directly and access them from through variables, a dictionary provides a key-value, where you access the value of data, through a key as the "index", but if the script the dictionary will exist in is the only one using it, that extra organization might add more complexity
And by a "private cached variable" I mean something like this:
public class SomeScript : Mono
{
public SomeReference CachedVar {return cachedVar;} //the private cached var is now accessed pubically from other scripts
[SerializeField] SomeReference cachedVar; //now the reference can be set in the inspector and access is private
//void Start() {cachedVar = FindObjectOfType<SomeReference>();} //this can be avoided entirely because of the above
}
If SomeScript needs to use something that would otherwise be stored in your dictionary, it can just call cachedVar or whatever the specific cache is, if something outside the class needs to access it, they can use the public property instead
it adds complexity? well maybe.. i kinda just wanted the strings so it seems nice and blue
easy to see and stuff
having a dictionary means you have to manage the dictionary to keep it up to date
which is doable, but means more juggling than just not having to do that
is it good to use when your main input is left mouse click?
Making a first person shooter, and made this script to move the gun between hipfire and sights positions. it works fine until i press right click while the gun is transistioning, when it starts to shoot back and forth between the position i clicked at and the position it was moving to. How can i fix this?
as example i want to create a Point and click adventure, where almost everything needs to bind mouse click left
I have two points A and B.... I want to create a third point that is in the direction from A->B with distance d... but I also want to move it a distance d2 in an orthogonal direction... what math am i missing?
Hi! i have a problem where i have a gameobject that instantiates another one, this one takes the rotation as a guide to where to go and also takes it as speed, does someone know how i can do it only take it as the vector it should follow and not the speed? (here is screenshot of code for reference)
normalize the vector and multiply by the desired speed
Vector2 direction = mouseWorldPosition - transform.position;
rb2dBullet.velocity = direction.normalized * speed;```
rotation isn't a great name for it since it's a direction vector. A rotation would be captured in a Quaternion or a float representing an angle around the z axis for example
so i should do direction instead?
I think it's a better name for what that is
i thought it might mess up if i try to rotate anything later on
but since its just a mini game for learning i didnt think twice
What you're missing depends on what you already have
gets a normalized version of the vector
and what is that?
a normalized vector is a vector with length 1
ohhhhhhh
yeamb lol 🚶
wouldnt it be v3 (4,4,4) normalized 1,1,1?
The idea is you can think of a normalized vector as basically representing only a direction and not a magnitude. So you can multiply it with any number to get the same direction with any magnitude you want
@mellow sigil I think I can just do offsetPos = new Ray2D(Vector2.zero, Vector2.Perpindicular(myDir)).GetPoint(distance);
yea yeah
very helpfull
ty my man
no the length of 1, 1, 1 is sqrt(3)
sqrt?
hmmm wait
lemme think rq
new vector 2 = 15 , 7.5
vector 2 but normalized would be 1, 0.5
oh
pythagorean theorem gets you the length
its .58 .58 .58 🙂
You take the squares of all the vector's axes (X, Y, Z), you add them, and square root the result. That's your length (magnitude)
OHHHH
No, it's a circle around the origin, not a square
Yes you can think of a normalized vector as a vector on the unit circle
A normalized 2D vector pointing 45° has X and Y at 0.707 or something
so - preserve the direction of the vector but get the one on the unit circle
and that's normalization
okay
so it would be like a way to make it always be the same without taking in account the distance from point 0 to point x in case it is the same direction?
the red is the normalized
right?
those are two different vectors and the red symbolizes the normalized part of each one
yes exactly
yay
normalized versions of them
very useful when you only care about the direction
or want to move something in a direction, since a normalizedVector * 5 would be 5 units in its direction
hi, im making a first person shooter, and made this script to move the gun between hipfire and sights positions. it works fine until i press right click while the gun is transistioning, when it starts to shoot back and forth between the position i clicked at and the position it was moving to. How can i fix this?
what are you coding in ohmy..
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
im on chromebook
how are you using unity on a chomebook..
just cause you can doesn't mean you should
also how are you even running Unity on chromebook
anyways idk how to fix that i think the two coroutines are conflicting because they are the same speed but because of the insights bool they shouldn't be able to be triggered at the same time
Simply block any transitioning if there is already one in progress
how?
boolean or null check a Coroutine variable
store coroutine inside variable
StartCoroutine returns a Coroutine
and i can check if a coroutine is already active?
check if its not null
only assign it null when the coroutine is done
what is the code for that?
private Coroutine m_transition;
...
private void Update()
{
...
if (m_transition == null)
{
m_transition = StartCoroutine(Foo());
}
}
private IEnumerator Foo()
{
...
m_transition = null;
}```
that basically
does anyone have a beer drinking script
Probably.
What have you tried and what isn't working
It's gonna be unique to how your game works, so we of course can't just make code for you (and this is a place of learning, so that isn't allowed anyway)
no but I have written many scripts while drinking beer
im trying to make consumable but i dont know how
There are tons of ways
Depends
you'd have to define exactly what that means
does it just disappear
do you need an animation of the drtinking happening
does it have some effect on the character?
It's as simple as reducing an int by one when you call Drink()
or increasing it
And as complex as an entire inventory system with animations and side-effects
Well, could be even more complex than that
like where you press on it with F and it drinks it with an animation
Make an animation and play it when you press f
interface <- consumable
It's still to vague to help with imo
which part of this are you stuck on
basically - tackle it piece by piece
Im trying to make it consumable like for it to dissapear when i press a button on it
yeah you said that, multiple times
still unclear which part you are struggling with though or what you have so far
so many different ways to do this its hard to answer definitely , you have to break down each part into smaller parts and tackle it that way
eg .
how to Do F press Key?
how to detect objects?
how to run method when found object etc.
Destroy(object)
Is there a way in a double switch case to disregard the second value, something like this?
Just add another case line for the second case
I think I meant this
if that,s the right syntax
yes discard should work
Ah yeah I misunderstood what you wanted. That is correct
thanks
How can I make an object instantiate at a position relative to its parent object. Currently my script is instantiating objects at the positions of detected objects instead of its position being dependant on the parent gameobject. Would I need to project on a plane to align them?
If you set the parent when instantiating then its local positional values will be relative to the parent
Yes, but currently the object I am instantiating is spawning at the position of the object detected. Although the coordinates of the instance are relative to the parent. My goal is to make the instance position along the local x and y coordinates along a plane.
also if its not a child and you want to relative to a other object its just addation
otherObjectPos + relativeOffset
Just zero out the local positional vector if you want it to spawn at the parent
even if you parent an object, if it already has an offset that just translate into a local offset
(another reason to make sure you prefabs don't have positional values)
use theParent.TransformPoint(desiredLocalPosition) to get the position to pass into Instantiate
If your entire game is literally only 1 input and you dont plan on supporting other devices like controllers, then maybe not, if you do plan to have other inputs or those inputs should be used by different devices or you just want control over input through events instead of polling in Update, then it can be useful and has a lot of nice built in features like toggling, rebinding, activating after some time has been held, normalizing raw input values, input states, etc - though in general, I would say its far better than the default input system, and since its become stable, I have personally only used the "new" input system in every project no matter how small just due to how flexible and scalable it is to work with
Does anyone know how to access nvidias dlss mode in script
Not sure if it's possibly to set directly, but you could probably define several hdrp assets that have different config of dlss and switch between them.
Hi! So I recently have been working on an action buffer system just so the player doesn't have to perfectly time back to back actions. This is what I have so far for my system. The only problem I have with it is it's precision. For example, when I input an attack in the middle, I want the 2nd attack to occur 0.3f after the first attack ends (or a value extremely close to 0.3f). However, currently the variance is around 0.01 I want the variance to be lower. I did some research and I've come to realize that Unity's Invoke method is not extremely precise. Is this true? If so, I was looking for some extremely timing precise alternatives!
It's more about the update loop. User code executes at certain place in the update loop(frame). The next time it executes is on the next frame, so .016ms later assuming 60 fps. You can't really control precise execution within these 0.016ms and shouldn't need to, because it wouldn't really have any impact on the game.
yes, you don't get ultra-precise timers
that would require unity to be able to interrupt whatever is happening to run your code
Sure, there's stuff like late update too, but you don't know how far in the frame that is executed.
don't use realtimeSinceStartup for gameplay purposes
would time.time work fine?
Yes. That should be the default.
got it thank you!
Out of curiosity, when do you usually use realtimeSinceStartup if not for gameplay?
I haven't used it recently at all
I see I see I'll do some research on that then xd
In the docs they provide an example of using it for an fps counter
public abstract class StorableHandler : MonoBehaviour { }
public abstract class StorableHandlerUI : MonoBehaviour
{
StorableHandler storableHandler; //UIManager should have references to both the slots and the inventory (StorableHandler)
List<SlotUI> slots;
public Init()
{
//init slots and bind events
slot.OnDroppedEvent += (fromIndex, toIndex)
=> OnDropCallback(fromIndex, toIndex);
}
protected void OnDropCallback(SlotUI slotFrom, SlotUI slotTo)
{
//how should I be getting the SlotFrom inventory reference?
}
}
public class SlotUI : MonoBehaviour, IDragHandlers, IPointerHandlers
{
//public StorableHandlerUI StorableHandlerUI <--- seems like I need some bi-direction reference binding
public event Action<SlotUI, SlotUI> OnDroppedEvent;
public virtual void OnDrop(PointerEventData eventData)
{
//We should swap objects between slots here, which also happens between different inventories
foreach (Component component in eventData.pointerDrag.GetComponents<Component>())
{
if (component is SlotUI slotUI && slotUI.StorableHandlerUI != null)
{
OnDroppedEvent?.Invoke(slotUI, this);
return;
}
}
}
}```
So, I've been redoing a lot more inventory logic and there's one thing I'm trying to understand and it's how I should have stuff reference when it comes to decoupling objects. My idea is to just bind my slots by events, which works out well until I get to my method of object swapping between inventories/managers. The only way I can think of managing this is by giving each slot a bi-directional reference, but that feels like doing everything by events here becomes obsolete and I should just then call by method.
It works fine if I just swap between slots in the inventory itself, but it becomes a problem when introducing swapping between different inventories.
I was recently working on an inventory-ui binding as well. The way I have it setup is that when I bind a certain inventory to ui, I subscribe the inventory ui to the actual inventory SlotChanged event as well as populate the UI inventory with InventorySlotUI elements that hold an index to the bound InventorySlot. So the Inventories communicate with each other by events/method calls, but the slots are controlled from the UI/actual inventory class respectively. The UI/actual slots only communicate with their ui/actual inventory respectively.
I'm trying to make a setting menu where you can change the framerate, and I'm stuck on 2 buttons. How would I turn V-Sync on, and how would I also let the user select an "Uncapped" frame rate?
targetFrameRate of 2 might be a tiny bit low 😛
That just means I don't know what to set it.
-1 is for uncapped (check the docs to confirm though) and there's a separate property for v-sync
The docs don't really explain it though.
And I don't know how to set V-Sync, based off players moniters hertz
okay... I'll give you links, but honestly this should be a quick google away
I've tried for the past 20 minutes
https://docs.unity3d.com/ScriptReference/Application-targetFrameRate.html - explains target frame rate and what -1 is and different platforms and everything
https://docs.unity3d.com/ScriptReference/QualitySettings-vSyncCount.html - v-sync
It doesn't explain how to get the player's monitor's hertz though, and change that to a vSyncCount
so, ready what vSyncCount does and what its values mean
What are you asking?
I'm not asking, you are 😛
I'm telling you to read the docs, they're explaining everything
The second link does. Read it...
When you use vSyncCount, Unity calculates the target frame rate by dividing the platform's default target frame rate by the value of vSyncCount. For example, if the platform's default render rate is 60 fps and vSyncCount is 2, Unity tries to render the game at 30 frames per second.
Wait so if a player has a monitor with hertz of 75, it will do (PlayerMonitorHertz / Vsynccount), which means if I set it to 1, then it will just use the players montior hertz right?
Yes
Thanks, for me reading complicated docs like that is kinda hard.
This is far from being a complicated doc😬
If you find it hard to understand, break it down to parts and research the terms that you don't know.
It's a good way of learning.
Well I saw here that is said "Platform", so I thought it meant the build's set frame rate, not the users.
Platform referes to the device that they run the game on, i.e. windows PC, Linux, PS5, Android, etc...
Thanks for that.
Got this code snippet. Anyone know where Delta.Multiply is from? Is that a Unity thing?
Not a Unity thing
Shit, then it could be…. Anything >_>
Well, hope the creator responds then.
I got the radar working mostly. Here
You mean like, a variable is only visible in unity if?
This won't change whether the field is serialized, but NaughtyAttributes provides an attribute that conditionally shows the field in the inspector
If you mean conditionally shown in inspector, then yes
conditionally serialized, no
Anyway use NaughtyAttributes https://dbrizov.github.io/na-docs/attributes/meta_attributes/show_hide_if.html
It's a third party asset.
editor plugin, yes
Well you could write the custom property drawer the same way the plugin does
Unity Editor was made to be extensible
oh right, just a custom property drawer (:
A custom editor for the entire component could make sense, though
in case you're unfamiliar:
- a property drawer defines how to draw a single property in the inspector
- a custom editor defines how to draw an entire component
Hey everyone I need help with coming up with a solution for:
Storing a connected “pattern” of connected tiles from a specific tile as the origin/pivot point.
And two, comparing that connected pattern to another identical connected pattern. (With or without rotational symmetry)
If someone has a solution or better yet a post or forum with a similar solution to study.
Just a List<Vector2Int> would do it for a basic solution
or HashSet of them
with two hashsets you know you can check if they're the same pattern with something like:
bool IsSamePattern(HashSet<Vector2Int> a, HashSet<Vector2Int> b) {
return a.Count == b.Count && a.IsSubsetOf(b);
}```
How would this work exactly? I’m not understanding, even with the code?
as for rotational symmetry I suppose you could just make a function to rotate the set and then test for this pattern sameness for each orientation
it's just a set of positions
the code checks if the two sets contain exactly the same positions
the positions are assumed to be expressed as "local" positions from a pivot point
In relation to a chosen position though.. like imagine a group of water tiles that make up the shape of a lake.. now how to find the same lake in a different position even if the rotation is different
well let's not worry about the rotation being different yet
that can be solved later
start with just the first part of the problem
can ytou explain the use case more?
are we talking about just a pattern of positions?
Or like, specific tiles as in a Tilemap
if you mean a certain pattern of tiles in a tilemap, that's essentially identical to a substring text search problem
You could use standard algorithms for example https://en.wikipedia.org/wiki/Boyer–Moore_string-search_algorithm
It’s for a tile based puzzle game.
Not a tile map. But am looking for a solution with a vector2int based..
Imagine for example a tile with the number “5”. That tile will need to contain 5 tiles including itself as a group of orthogonal connected tiles.
But if there are two “5” on the grid and I want the player to try to create identical groups. I needs to check that.
I suppose checking that is kinda easy but I want to engineer it in a way that is easily packaged to check for other characteristics like symmetry/color/etc
you are not asking for pattern matching but search if there exists another subgraph in your tilemap which is same for some given subgraph
btw since it is tile based so you can use translation and rotation to see if two sets of vertices match.
that feels like a better answer than mine!
So yes, I’m struggling to convey what I’m looking for. But yes, if I already knew what this problem was called I would have googled it already.
And to respond to your answer, that link is so confusing to me lol
Are you familiar with graph theory yet?
You'll really want to be, if you're making a tile based... anything game
Not so much but reading it totally makes more sense now but I’m struggling on how to structure it in Unity.
well i figured out the problem. i whole thought i assigned references in the inspector, and lo, i did not
sometimes all you need is to come back with a fresh set of eyes
So reading more about this I would create a system that looks at a tile to the left (example) of center, checks to see if it is “connected” if it is, it stores a relation to it?
Wouldn’t this be over kill? Many tiles will contain the same data even though it’s not needed.. especially on an orthogonal grid..? @leaden ice
Your actual graph should only contains the nodes that actually exist, so there shouldn't be redundant data.
Sure, but what about four tiles connect into a square. There are 8 different data points, right?
*2 because of relationships
So are you counting relationships or nodes?
Each node would have several relationships(edges), but the total count of nodes wouldn't change.
Both but can’t it be simplified to something like 4
Sure it can. A node is an object. It can have all kinds of properties, for example a list of edges. Each edge references 2 nodes that it connects.
Or you could have the edges as references to the connected nodes instead. The concept doesn't change.
you can store all AABBs, offset, vertices count of all connected components, then check if one AABB X can be rotated and translated to another AABB Y and vertices count is the same, if yes, then try to map the vertices of X to Y by apply the same translation and rotation
In the “2x2 square” example. You can either save the data with relationships which is 2 per tile in example. But can’t you do a string like “bottom left to bottom right to top right to top left?
So how would I actually write code for that to work? I’m a beginner. What’s the process look like
First of all, what does a graph has to do with a grid or tiles? Is it an indispensable part of the mechanic that you want to implement?
Ahhh I see, using translation of position.. I like this idea
Or, I guess, I'm not entirely sure what the question is.
A graph is simple:
Graph
{
Node[] nodes
}
Node
{
Node[] neighbors/connectedNodes;
}
Then you can do whatever you want with it.
So checking the same amount of relations is the first check to prevent unnecessary calcs. Then if the same translate the pivot position to the other position, subtract the difference from all verts and compare… this works without symmetry though easily. Rotational seems complicated
Oh I see. Then it stacks like a tree.. how would you use rotational symmetry on nodes?
But I also need to know the direction right? If it has 2 connected nodes, I would need a check to see the direction of them yes? Or easier way
I've no clue what a "rotational symmetry node" is.
No. rotational symmetry on the entire tree of nodes.. all nodes make up a body of orthogonal adjacent verts. I want to check if that “shape” is the same as the other shape with or without symmetry
Sure, you could check the direction with connectedNode.position - this.position. maybe even cache it as a key/value of a dictionary that contains the neighbors.
I have an example game that performs this task that I want. Should I share that with you to help understand?
Comparing graphs might be tricky.
If it's a video, sure.
Are you aware of the pixel puzzle game “taiji”?
Nope
https://youtu.be/Og4zPwrhb5w?feature=shared
Go to 36:00 flat.
Look at the shapes with a “/“ symbol. They are rotational symmetrical
Taiji, developed by Matthew VanDevander, with music by Grzegorz Bednorz, is a puzzle game in the style of The Witness.
Explore an abandoned island and solve over 400 puzzles!
This playlist:
https://www.youtube.com/watch?v=MB5W_QgmBwQ&list=PL-6OfVGjf7cusu4YALsev03RNl-UA7MhL
#taiji #puzzle #letsplay
@cosmic rain
@cosmic rain did you see it at 36min?
Yes, but I don't really understand what's going. All I can say, that it if you need to match a certain pattern, perhaps just compare grids.
Or 2d arrays
I see that they seem to be the SAME rotation, but it didn't look symmetrical to me..
It honestly looked Asymmetrical
Edit: I get it now
Ok quickly, look at the thumbnail of the video. See the Taiji logo? Blue L and white L? They are flipped and the “dot” in the L’s is rotational symmetrical.
Think of the dot as the pivot point. And then I need to store the shape relative to the pivot and then rotate the shape to see if It matches
Comparing grids makes no sense in this case.
they are rotated. and symetrical ( not symetrical in relation to the other, just symetrical). i know it's hard to see if you arent familiar with the game. but when he solves it, pause. the unshaded cells also count as their own shape as well. every symbol "/" has to be the same shape doesnt matter if its rotated
See my edit. I already got it. I thought you meant the / themselves were rotated
So they have an opposite rotation, but the same shape
well yes, more specifically they can have a 90, 180, -90 degree rotation and still count as long as the symbol in the same is relative to the rest of the shape
You'd need to iterate the nodes and rotate their position relative to the pivot point.
ok. so? lol
awesome lol
i will draw a small example very quickly..
So... comparing grids seems exactly like how to do it..
look at this. so both shapes are the same as a "shape" but also relative to their "dot"
@cosmic rain @spring creek @leaden ice
Assuming you know the position of the node, you can rotate the grid and compare to the other shape.
Compare, rotate. Repeat 3 times, then compare again, if it was not equal in any of the instances, it's not equal.
rotate the whole grid? isnt their something better? what if this becomes more complex with more shapes and differnt types of dots. how can i save these shapes separatly and then rotate them when i want to compair them?
save just the shape and its data related to the dot.
Well, you'd need some way to isolate a shape into a separate grid
i want to use Vector2Int if possible. not a grid. just positions and relations
I mean, you have a grid there initially already.
Besides, using Vector2Int and disregarding the whole grid is gonna make things more complicated
It's definitely not impossible. With graphs you can do it the way you want, but I think tis gonna be more complex than just comparing grids.
wait, hold up, there has to be a way of doing it the way im talking about. imagine this grid with only the two dots. no colors.
when the player clicks "check" i want to scan the grid for all "dots" then start comparing if the shapes are the same. is there an easier way? i'm not understanding
storing the relation mean you want to introduce one more mapping to form the edge, probably get thing worse since you still need to map those edges by translation and rotation
i dont understand
You get each shape on your grid and put them on their own grid with the dot being the center. Then you rotate the grid and compare to another similar grid. The comparison is straightforward. Just loop through the grid and check if a position corresponds to a position of the other grid.
that makes sense that it would work, it just seems so not elegant lol seems like a "let me whip this up real fast" kinda solution. no disrespect lol
The simplest solution is often the best solution
eg if you have a shape (X means nothing)
BAA
XAX
and you want to store some relations eg position relative to B and you get 0,0 1,0 2,0 1,1
then you have another shape
XC
CB
XC
you get 0,-1 -1,0 0,0 0,1
you still need to apply translation and rotation to those "relation"
wait, can they match each other.....just in case the pivot is not the same
bro what is this BAA XAX stuff lol sounds educated but you are speaking to someone who clearly is not educated in this way. very difficult to follow you
imagining the letters are inside a grid
so just put them in seperate grids with the pivot in center then start checking all 4 rotations of the grid until it either matches or none of them match?
you can read my AABB solution.....should be slightly faster by filtering the AABB
where in the grid?
is AABB just some arbitrary combination of imaginary shape? i don't understand AABB in relation too? all i see is a two pair
https://ychef.files.bbci.co.uk/624x351/p0102gs2.jpg
RRX
RRX
GGX
PGG
the leftmost 3 columns, X means empty again
ah ok i see what you mean now.
so back to this, now i don't understand the array of integers. can you explain that
array of vector2
position relative to B
ie if you add the position of B and the element then you get the position of another tile
0,0 1,0 2,0 1,1
B is pivot, then B +1, then B + 2, etc?
and i=to answer this, they can not match if pivot is not the same ( even if the shape is identical)
(0,0) , (1,0) , (2,0) , (1,1)
BEF
XGX
E position is position of B + (1,0)
F position is position of B + (2,0)
ok yes i understand. and how do you apply rotation to this array?
just to be completly sure:
G position is position B + (1,-1) ?
rotate the vectors in the array
eg
XX AX
BA to BX , offset of A to B (1,0) will become (0,1)
yes, G position is position B + (1,-1), mb
ok so what if the shape is not rectangular instead looks like this:
X = empty
A = connected
P = pivot
XAAAP
XXAXX
XXXXX
----
PXXXX
AXXXX
AAXXX
AXXXX
XXXXX
thes two shapes are correct. imagine without X's
how to rotate this?
here without X's
AAAP
A
----
P
A
A A
A```
try all possible rotations (4), or use AABB (4,2) vs (2,4) then only two rotations
AAAP
XAXX
will be bounded by 4 x 2 (columns x row) AABB and
PX
AX
AA
AX
will be bounded by 2 x 4 AABB
i type X because letters seems to be aligned better
keep in mind, the shape to draw is up to the player.. so it could have a dimention of 6x2 or 9x3 (with some empty cells of course)
so i would first do a check to find all connected cells.. then get the dimentions from that. eg 3x5
i could then compair dimentions first, if they are differnt flip them and compair again.. if the same, then start cycling through the matrix?
Yes
Though i would suggest you keep a list of AABB and each time you add/ remove tile then see if two or more connected component can be merged/ separated and merge/ split the AABB
its giving me an error CS1503 any fixes?
using UnityEngine;
namespace GenshinImpactMovementSystem
{
public class Player : MonoBehaviour
{
private PlayerMovementStateMachine movementStateMachine;
private void Awake()
{
movementStateMachine = new PlayerMovementStateMachine();
}
private void Start()
{
movementStateMachine.ChangeState (movementStateMachine.IdlingState)();
}
private void Update()
{
movementStateMachine.HandleInput();
movementStateMachine.Update();
}
private void FixedUpdate()
{
movementStateMachine.PhysicsUpdate();
}
}
}
Where is it giving the error and what does the error say?
Oh, and don't crosspost.
One channel per question
It is DEFINITELY not #archived-code-advanced 😸
- Share the !code properly. Refer to the bot message below.
- Configure your ide properly. Refer to the next bot message.
- Learn to read and understand the error message. No one remembers the errors by their code, but the message should provide enough info to fix the error.
- The issue is a simple syntax error. If your ide is configured properly, you would see it underlined.
📃 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.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Ah I see you fixed the syntax error(was basing my reply on the screenshot in the advanced channel).
please do not cross post
ok
in ECS, how do I move an entity in its forward axis? LocalTransform.Translate is giving me trouble
Well, what are the errors?
Judging by the coloring, Forward is probably a method, so you need to call it properly.
Yep. Looks like what I said
