#archived-code-general

1 messages · Page 282 of 1

latent latch
#

usually you go with observer pattern for that

#

so updating a source updates everything that relies on it

merry stream
#

can you explain more? do I do that using events?

#

that's what I do currently for that type of situation

latent latch
#

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

wicked scroll
little meadow
#

yep, yep, it's a common thing - first you use snapshotting, then you try to get away from it 😄

wicked scroll
#

whynotboth

merry stream
#

so if I want an ability to do 90% base damage i could set it to 90

latent latch
#

then force a recalc of that ability specifically to cache

merry stream
#

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

latent latch
#

flat -> percentage -> additional percentage

merry stream
#

yes

latent latch
#

if an ability shouldnt do damage then don't flag it as having damage, so it wont subscribe to damage

merry stream
#

so have these events subscribe on the ability SO itself?

#

then if it's a damaging ability, it passes that damage to the DamageEffect?

latent latch
#

right, each ability will subscribe to your modifier handler

merry stream
#

so my effects should be Valueless

#

makes sense, I think you said that earlier

latent latch
#

yeah, craft it internally, but have tags on it still to tell it what extra modifiers (from your handler) it can subscribe to

merry stream
#

enum as the tags?

latent latch
#

enum flags

merry stream
#

what is that?

#

never used that

latent latch
#

it's quick enum comparison

#

for when you have tons of flags

#

better known as bitwise enum (probably have used them for layer masks)

heady iris
#

a "flags" enum has values of 1, 2, 4, 8, 16, ...

merry stream
#

so I can use logical operations on them?

heady iris
#

you can turn on or off 32 different bits

latent latch
#

good read

heady iris
#

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?

latent latch
heady iris
#

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

heady iris
#

Oh

#

I did not read the freaking manual!

#

Thanks!

latent latch
heady iris
#

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

lean sail
heady iris
#

nah, GenericPool just uses () => new T() as the create function

#

but all I need to do is make CoolerGenericPool that exposes what I need

quaint rock
#

any reason to not just define the create yourself in ObjectPool<T>

heady iris
#

not really

#

and I should probably actually do that

quaint rock
#

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

dense estuary
#

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

leaden ice
dense estuary
leaden ice
#

OverlapCapsule is simpler actually

#

basically you just do a really tall capsule with the chosen radius

#

tall enough to cover all possible y positions

dense estuary
#

Oh, well, that sounds perfect.

#

Thank you :D

ornate perch
#

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

leaden ice
#

List<WhateverType>

ripe mountain
leaden ice
#

as long as WhateverType is a script you have on all the prefabs, or is GameObject itself.

ornate perch
#

Sure, i guess ill have to try a list itself instead of an array

leaden ice
leaden ice
#

either one

ornate perch
#

it still gave Type mismatch hm

ripe mountain
cosmic rain
leaden ice
leaden ice
ornate perch
#

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

ripe mountain
leaden ice
#

it's y, x. Double check that against brackeys

ornate perch
cosmic rain
leaden ice
#

how about capturePoints = FindObjectsOfType<CapturePoint>();

ornate perch
ornate perch
leaden ice
#

how are you assigning the array or list data?

#

if not that

ornate perch
#

right now im just trying to drag the prefaps into the list

#

in editor

leaden ice
#

and when you drag it, it immediately says type mismatch?

ornate perch
#

yes

leaden ice
#

try restarting Unity

ornate perch
leaden ice
#

Also just to make sure - CapturePoint is a MonoBehaviour class?

ripe mountain
ornate perch
dense estuary
leaden ice
#

that's a layer mask parameter

#

you give it a LayerMask

#
public LayerMask myMask;```
dense estuary
ripe mountain
leaden ice
# dense estuary

LayerMask converts implicitly to int
Trust me, pass a layermask in

ornate perch
leaden ice
#

(the number of colliders it found)

#

not a bool

#

you can't do if (int)

#

only if(bool)

dense estuary
#

oh, sorry.

dense estuary
# leaden ice it returns an int

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?

cosmic rain
#

Just to make sure, you're not dragging in objects from the scene hierarchy, do you?

thick terrace
ornate perch
#

it works if i use the prefab from my project

cosmic rain
ornate perch
#

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

dense estuary
somber nacelle
dense estuary
#

If I need to access the positions of objects in a overlap capsule, would it be better to use the normal one?

somber nacelle
#

why? the non alloc method provides that information too

latent latch
#

always non-alloc :)

dense estuary
#

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. } }

somber nacelle
heady iris
#

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)

dense estuary
heady iris
#
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

cosmic rain
dense estuary
#

to save for later

heady iris
#

this means that it has to allocate a new array each time you run it

heady iris
#

you probably then use the array once and throw it out

#

so it gets garbage-collected later

cosmic rain
# dense estuary Setting away space for data

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.

heady iris
#

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

cosmic rain
#

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.

heady iris
#

indeed

cosmic rain
#

Then you get games that require 32GB RAM for no particular reason

dense estuary
#

That all makes much more sense

heady iris
#

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

proper trellis
#

ok so like
how would i get RenderSettings to serialize in a json

#

its a type, so it wont work

cosmic rain
heady iris
#

RenderSettings isn't an object

#

so yeah, you can't serialize it

proper trellis
heady iris
#

I presume you want an instance of RenderSettings

dreamy wave
#

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.

rigid island
#

or are you doing UI for the page

dreamy wave
#

Rn I don't, but I do plan on modelling my own with the pages being their own separate objects.

dreamy wave
lean sail
#

this would mostly just be animation work then

heady iris
#

how do I make it open automatically to just one page

#

animate the book opening!

#

i'm unclear what the problem is

dreamy wave
#

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

heady iris
#

sure

#

you'll need some logic to make the book grabbable in the first place

latent latch
#

you can probably do it all with the animator

dreamy wave
#

alr ty guys

#

❤️

dense estuary
#

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); } }

heady iris
#

Destroying and instantiating icons every single frame will be producing a lot of garbage

#

But it's a perfectly valid place to start

cosmic rain
#

We're not sure what you mean by "clear and create" too. Are you actually referring to instantiating?

dense estuary
#

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.

cosmic rain
#

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.

proper trellis
#

cant figure it out

cosmic rain
dense estuary
proper trellis
#

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

heady iris
#

okay, but you don't want to serialize a type

#

the problem is that all of its properties are static

proper trellis
#

the data is never gonna be modified after its saved, so i just need the data

heady iris
#

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

dense estuary
#

I can't think of any, but I am experiencing a problem

cosmic rain
dense estuary
#

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

proper trellis
heady iris
#

The line numbers are off because you excluded the using directives

cosmic rain
proper trellis
cosmic rain
#

If you need to save the data in it, store it in an instance of your own type.

heady iris
#

oh yeah,RenderSettings derives from UnityEngine.Object

#

for...some reason

proper trellis
#

idk why

heady iris
#

you will need to copy the data you need out of it

dense estuary
proper trellis
#

just would always error about smth

heady iris
#

well, what was the error?

#

"about smth" is not meaningful

cosmic rain
heady iris
#

there's no reason you can't just make your own class to hold the data and serialize it

proper trellis
#

i remember one was just a "null reference exception" like nothing else just that

proper trellis
#

another was smth with json encoding, it seems to freak out abt colors

heady iris
#

OverlapCapsuleNonAlloc returns the number of hits

#

It doesn't change the length of the array (that would be impossible)

heady iris
cosmic rain
heady iris
#

A foreach loop will give you every item in the array, including items that were never assigned to by OverlapCapsuleNonAlloc

cosmic rain
proper trellis
#

as it was already becoming too much of a problem

#

then i asked here

cosmic rain
heady iris
#

well, we can't tell you very much if you deleted everything

proper trellis
#

i think i still have the script

#

thats the class i made

dense estuary
proper trellis
heady iris
#

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.

cosmic rain
tawny elkBOT
proper trellis
heady iris
#

do not derive DimensionRenderSettingsObject from UnityEngine.Object

#

just make it a plain old class

#

don't derive DimensionRGBColor from it either

proper trellis
#

still cant copy over the data due to due this???

#

cant figure it out

heady iris
dense estuary
#

whats the difference between ++i and i++?

heady iris
#

nothing in this case

dense estuary
#

oh

heady iris
#

I just use prefix by force of habit

dense estuary
#

sorry

heady iris
#

The loop condition is not i < overlapResults.Length

#

the condition is i < hits

cosmic rain
dense estuary
#

OH

heady iris
#

The overlap method stores each collider it hits into the array. That's all it does.

dense estuary
#

I GET IT

heady iris
#

So if it doesn't fill the array, you have random trash left in it

proper trellis
toxic bramble
#

Does anyone have a key door system

dense estuary
cosmic rain
spring creek
# toxic bramble Does anyone have a key door system

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

dense estuary
#

That makes so much sense

#

Thank you so much!

#

Ill work more on that tomorrow. I got to go to bed I have exams.

proper trellis
#

thx

proper trellis
# proper trellis YES OMG I GOT IT WORKING

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

cosmic rain
#

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.

proper trellis
cosmic rain
#

Then make a check. If it's null serialize DataWithoutLighting. If it is not, serialize DataWithLighting.

proper trellis
#

i just wanna know if i can essentially have an if statement in the table, so i dont need to do that

cosmic rain
#

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.

proper trellis
cosmic rain
#

Just kidding. But the use of tables is not appropriate here as you serialize objects.

#

It's not.

proper trellis
#

oh wait is it an array

cosmic rain
#

What's the type?

#

Ah, I see

#

It's an anonymous type

#

In either case, it's an object, not a table.

proper trellis
cosmic rain
#

But to answer your question, no you can't use a bool inside, as it's basically an initialization of the object.

proper trellis
#

oh ight

cosmic rain
#

You'll need an explicit type if you want to add some logic like if statements

faint nimbus
#

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?

orchid abyss
#

how to use collider variable outside oncollision enter?

faint nimbus
#

like how we can make invisible non physical circles for groundcheck and set the radius

cosmic rain
faint nimbus
#

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?

cosmic rain
#

Singleton pattern might make it easier to access it, but it's not necessary.

faint nimbus
#

ah okok UnityChanOkay

#

thank you dlichUnityChanSalute

hasty canopy
orchid abyss
cosmic rain
spring creek
#

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 ❤️

cosmic rain
#

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

sudden portal
#

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?

fervent furnace
#

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....?

knotty sun
sudden portal
#

Initiative values are static and determined before scene launch.
@fervent furnace yes exactly.

fervent furnace
#

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

knotty sun
#

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

sudden portal
#

@knotty sun You mean "LinkedList<T> Class"? What's the difference to a regular List for my project? Looks promising!

cosmic rain
#

I mean,even a regular list would work

sudden portal
#

@fervent furnace Either re-calculate the list or only have new characters in the next cycle (after all other characters had their turn once)

cosmic rain
#

You can just insert new characters into the list in the right place

knotty sun
fervent furnace
#

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

sudden portal
#

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

knotty sun
sudden portal
#

@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.

knotty sun
sudden portal
#

@knotty sun why? and what would level / position mean in this case?

knotty sun
#

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

sudden portal
#

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?

knotty sun
#

that is where linked list shine.
update [3] to point to [6] and [6] to point to [4]
job done

sudden portal
#

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

knotty sun
#

although you should never need to do that if you use that class

cosmic rain
#

And it rarely is.

sudden portal
#

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?

cosmic rain
chilly surge
#

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.

sudden portal
#

Would List

var store = listName[6|
listName.RemoveAt(6)
listName.Insert(4, store)

not work in my case?

cosmic rain
#

Yes that should work

#

Do note that indices would shift after inserting/removing

molten timber
#

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

sudden portal
molten timber
#

could you help me dlich

#

please

#

its so anyoinng

cosmic rain
cosmic rain
molten timber
#

yeah i could screen share if you got time

#

but i am gonna be muted

#

but i will hear you

#

@cosmic rain

magic briar
#

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

cosmic rain
molten timber
#

@sudden portal i am in school

molten timber
molten timber
#

@cosmic rain

cosmic rain
tawny elkBOT
molten timber
#

do you want everything

dense tusk
#

boi

molten timber
#

like that?

dense tusk
#

pause

#

use one of the links he sent you to paste your code there

molten timber
#

oh

#

my bad

dense tusk
#

lmao all good

molten timber
#

@cosmic rain

cosmic rain
molten timber
#

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

dense tusk
#

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

cosmic rain
molten timber
#

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

cosmic rain
dense tusk
#

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

cosmic rain
nocturne wyvern
#

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

lean sail
# dense tusk all my fellas, i'm trying to have my player transition to a location which i hav...

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)

stable kayak
#

does anyone have an elegant solution to auto tiling?

molten timber
sudden portal
molten timber
#

hahah

thin aurora
#

If you are certain the error is not the case, I can only assume the endpoint does something wrong

molten timber
#

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

thin aurora
#

Perhaps you supplied the parameters incorrect?

nocturne wyvern
thin aurora
#

Maybe that Parse method that is used does something wrong

molten timber
#

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

thin aurora
molten timber
#

spamming?

#

sent it twice

thin aurora
#

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

floral notch
#

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

floral notch
#

Dang

#

I just want to make tiles that behave differently when you touch them

#

not make it so they cause weird collisions

thin aurora
#

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

floral notch
#

am I missing something obvious

thin aurora
#

Sorry, no idea. This is better suited for another channel

floral notch
#

which one

floral notch
knotty sun
floral notch
#

collisions seem to make it like you're physically smacking the tile

#

and it applies a force against you

knotty sun
#

yes, imagine running into a brick wall irl

floral notch
knotty sun
#

yes, they are called triggers

floral notch
#

Oh interesting. I can see that option on my player box collider but not on the tilemap collider

#

does it only work with box

ripe mountain
#

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?

floral notch
#

because right now it seems to not work without it

knotty sun
#

no, you still need the rigidbody2d

floral notch
#

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

orchid abyss
#

why do i always get "type mismatch" when assigning my player attribute manager to a prefab?

warped condor
#

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

thick terrace
cosmic rain
warped condor
thick terrace
warped condor
#

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)

thick terrace
#

that's the one that used to be plastic right? i think it'd be an "xlink" in plastic?

wise geyser
#

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

ember lance
#

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

hexed pecan
ember lance
placid summit
#

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?

elfin tree
#

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?

heady iris
#

What does your hierarchy look like?

hexed pecan
thick terrace
heady iris
#

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)

placid summit
heady iris
#
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();
    }
}
hexed pecan
heady iris
#

yeah, the UGUI classes are (reasonably) friendly to extension

placid summit
#

I have to do it for circular hit detection - the rectangular-only is a bit rubbish!

sudden stump
#

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;
            }
        }
    }
}```
covert swift
#

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

sudden stump
#

@placid summit That bad?

placid summit
# sudden stump <@422737402113818635> 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

leaden ice
#

you also don't need .gameObject in anything in DamageOnCollision

#

and you should use intermediate variables instead of constantly calling GetComponent over and over

soft shard
leaden ice
#

Learn about TryGetComponent too

sudden stump
leaden ice
#

Why

sudden stump
#

I didn't know whether the code was going to stay or not, since this is still the prototyping phase

leaden ice
#

Why would you write the code bad intentionally

sudden stump
#

So I just wanted to write something as quickly as possible

leaden ice
#

whether it's staying or not

#

it's much faster to not rewrite GetComponent 80 times

sudden stump
#

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?

leaden ice
#

Anyway why ask for a code review with code you haven't already cleaned up

leaden ice
#

not just the GetComponents

#

the .gameObjects too

sudden stump
#

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)

leaden ice
tired elk
#

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

leaden ice
#

so you don't have this weird hard dependency between the scripts

sudden stump
#

Hmm, actually that's a good point. Another thing to read up on (or just use C#'s events)

leaden ice
#

Yes I mean C# events

placid summit
#

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.

sudden stump
leaden ice
sudden stump
#

And I don't see the point in making 20 components then keeping a main Player/Enemy/Object one for calling stuff

covert swift
leaden ice
#

I have never seen someone come in here with a framerate issue and the reason for it was GetComponent

#

It's a non-issue

sudden stump
#

^

#

Besides, my game's going to have low poly and textures, and those are the worst for performance

placid summit
#

ok that is good - depends of type of game of course

oblique spoke
ripe mountain
#

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

sudden stump
ripe mountain
#

can you see anything wrong?

sudden stump
#

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

oblique spoke
soft shard
scarlet shoal
#

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?

thin aurora
elfin tree
#

Anyone knows why this code DOES hit the layerMask it should be ignoring?

thick terrace
elfin tree
thick terrace
#

i think that should do it yeah

hexed pecan
#

Also your mask seems inverted

elfin tree
#

LayerMask.GetMask("Tower Range"); correct?

hexed pecan
#

It doesn't ignore those layers. It's the opposite - it includes only the layers in the mask

elfin tree
#

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

latent latch
gusty aurora
#

How to know when a prefab is instantiated ?

#

Some callback that gets called when a prefab is dragged from the project into the hierarchy ?

latent latch
#

Maybe one of the enabling callbacks would be called

#

Such as OnEnable or OnValidate

gusty aurora
#

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

latent latch
#

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

gusty aurora
#

It feels so ultra mega clunky

#

I can't believe there is no simple callback when a prefab is instantiated

elfin tree
#

Is there a way to ignore certain layer for OnMouseEnter and similar methods?

thick terrace
elfin tree
#

Do you know if something on the Ignore Raycast Layer will detect collisions?

leaden ice
late lion
elfin tree
hexed pecan
#

Or make a serialized field and assign it in the inspector if that's possible

elfin tree
leaden ice
#

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)

elfin tree
#

ahhh in my case it's in a canvas so i'll use graphic raycast

leaden ice
#

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

leaden ice
elfin tree
#

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)

leaden ice
#

Is this an actual physics collider?

elfin tree
leaden ice
#

exclude it on the physics raycaster

elfin tree
#

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

leaden ice
#

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

swift falcon
#

hey thanks i will look into the action map asset, sounds interesting

elfin tree
#

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);
            }
        }
icy depot
#

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

soft shard
elfin tree
soft shard
elfin tree
#

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

icy depot
leaden ice
#

Is the raycast not hitting? Is the code not running at all?

grave tundra
#

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)?

elfin tree
leaden ice
#

Put a log before the raycast

elfin tree
#

ohh

leaden ice
#

like maybe this whole function is inside something like:

if (!EventSystem.current.IsPointerOverGameObject())```
#

which would explain everything

elfin tree
#

it is

leaden ice
#

yep

#

makes sense

#

because with the physics raycaster now the event system sees the physics objects

elfin tree
#

i mean, there's an inverted if

leaden ice
versed spade
#

Would it be a good idea to make a seperate script under my player object for movement and then another for combat?

elfin tree
#

oof i wish that part was my code, will see what i can do it's not too complex i think

#

ty!

versed spade
#

Just was thinking. "God I wouldn't want to read this again" if I put it all in one script lol

spring creek
#

Separation of Responsibilities is pretty powerful.

sudden stump
elfin tree
#

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

sudden stump
#

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

soft shard
# icy depot I'll cache all of my stuff in a nice dictionary so i can access it with string t...

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

icy depot
oblique spoke
soft shard
# icy depot i dont get what the private cached variable and the references without a key-val...

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

icy depot
#

it adds complexity? well maybe.. i kinda just wanted the strings so it seems nice and blue

#

easy to see and stuff

hard viper
#

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

swift falcon
somber sparrow
#

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?

swift falcon
#

as example i want to create a Point and click adventure, where almost everything needs to bind mouse click left

grave tundra
#

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?

tall salmon
#

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)

leaden ice
#
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

tall salmon
#

so i should do direction instead?

leaden ice
#

I think it's a better name for what that is

tall salmon
#

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

mellow sigil
tall salmon
#

btw srry if i ask but

#

what does normalized do?

leaden ice
tall salmon
#

and what is that?

leaden ice
#

a normalized vector is a vector with length 1

tall salmon
#

ohhhhhhh

rigid island
#

yeamb lol 🚶

tall salmon
#

wouldnt it be v3 (4,4,4) normalized 1,1,1?

leaden ice
#

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

grave tundra
#

@mellow sigil I think I can just do offsetPos = new Ray2D(Vector2.zero, Vector2.Perpindicular(myDir)).GetPoint(distance);

tall salmon
#

very helpfull

#

ty my man

leaden ice
tall salmon
#

sqrt?

leaden ice
#

square root

#

sqrt(3) == ~1.77ish

tall salmon
#

hmmm wait

#

lemme think rq

#

new vector 2 = 15 , 7.5
vector 2 but normalized would be 1, 0.5

leaden ice
#

no

#

that doesn't have a length of 1

tall salmon
#

oh

leaden ice
#

pythagorean theorem gets you the length

tall salmon
#

alright now

#

lemme pull up paint rq

#

XD

rigid island
simple egret
#

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)

tall salmon
#

thats what im understanding

leaden ice
#

the diagonal line is 1

#

the sides don't have to be

tall salmon
#

OHHHH

simple egret
#

No, it's a circle around the origin, not a square

leaden ice
#

Yes you can think of a normalized vector as a vector on the unit circle

tall salmon
#

oh yeah i learned that in maths

#

true

simple egret
#

A normalized 2D vector pointing 45° has X and Y at 0.707 or something

leaden ice
#

so - preserve the direction of the vector but get the one on the unit circle

#

and that's normalization

tall salmon
#

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?

leaden ice
#

yes it's just the direction

#

without the distance

tall salmon
#

the red is the normalized

#

right?

#

those are two different vectors and the red symbolizes the normalized part of each one

leaden ice
#

yes exactly

tall salmon
#

yay

leaden ice
#

normalized versions of them

tall salmon
#

i got it

#

ty my man

#

was nice having some help

quaint rock
#

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

somber sparrow
#

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?

rigid island
#

!ide

tawny elkBOT
somber sparrow
rigid island
somber sparrow
#

im coding on the linux terminal

#

the haters said i couldn't do it

rigid island
#

just cause you can doesn't mean you should

#

also how are you even running Unity on chromebook

somber sparrow
#

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

wide dock
wide dock
#

boolean or null check a Coroutine variable

rigid island
#

store coroutine inside variable

somber sparrow
#

huh ive never heard of hat

#

that

rigid island
somber sparrow
#

and i can check if a coroutine is already active?

rigid island
#

only assign it null when the coroutine is done

somber sparrow
#

what is the code for that?

wide dock
#
private Coroutine m_transition;

...
private void Update()
{
  ...
  if (m_transition == null)
  {
    m_transition = StartCoroutine(Foo());
  }
}

private IEnumerator Foo()
{
  ...
  m_transition = null;
}```
rigid island
#

that basically

eager tide
#

does anyone have a beer drinking script

spring creek
leaden ice
eager tide
#

im trying to make consumable but i dont know how

spring creek
#

Depends

leaden ice
#

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?

spring creek
#

It's as simple as reducing an int by one when you call Drink()

leaden ice
#

or increasing it

spring creek
#

And as complex as an entire inventory system with animations and side-effects

#

Well, could be even more complex than that

eager tide
#

like where you press on it with F and it drinks it with an animation

spring creek
rigid island
#

interface <- consumable

spring creek
#

It's still to vague to help with imo

leaden ice
#

basically - tackle it piece by piece

eager tide
#

Im trying to make it consumable like for it to dissapear when i press a button on it

leaden ice
#

yeah you said that, multiple times

rigid island
#

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.

elfin tree
#

Is there a way in a double switch case to disregard the second value, something like this?

somber nacelle
elfin tree
#

if that,s the right syntax

leaden ice
#

yes discard should work

somber nacelle
#

Ah yeah I misunderstood what you wanted. That is correct

elfin tree
#

thanks

dense estuary
#

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?

latent latch
#

If you set the parent when instantiating then its local positional values will be relative to the parent

dense estuary
quaint rock
#

also if its not a child and you want to relative to a other object its just addation

#

otherObjectPos + relativeOffset

latent latch
#

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)

leaden ice
soft shard
# swift falcon is it good to use when your main input is left mouse click?

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

clear oriole
#

Does anyone know how to access nvidias dlss mode in script

cosmic rain
ivory cove
#

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!

cosmic rain
#

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.

heady iris
#

yes, you don't get ultra-precise timers

#

that would require unity to be able to interrupt whatever is happening to run your code

cosmic rain
#

Sure, there's stuff like late update too, but you don't know how far in the frame that is executed.

heady iris
#

don't use realtimeSinceStartup for gameplay purposes

ivory cove
heady iris
#

Yes. That should be the default.

ivory cove
#

got it thank you!

#

Out of curiosity, when do you usually use realtimeSinceStartup if not for gameplay?

heady iris
#

I haven't used it recently at all

ivory cove
#

I see I see I'll do some research on that then xd

cosmic rain
#

In the docs they provide an example of using it for an fps counter

latent latch
#
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.

cosmic rain
# latent latch ```cs public abstract class StorableHandler : MonoBehaviour { } public abstract...

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.

royal wigeon
#

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?

little meadow
#

targetFrameRate of 2 might be a tiny bit low 😛

royal wigeon
little meadow
#

-1 is for uncapped (check the docs to confirm though) and there's a separate property for v-sync

royal wigeon
#

And I don't know how to set V-Sync, based off players moniters hertz

little meadow
#

okay... I'll give you links, but honestly this should be a quick google away

royal wigeon
#

I've tried for the past 20 minutes

little meadow
royal wigeon
little meadow
#

so, ready what vSyncCount does and what its values mean

royal wigeon
#

What are you asking?

little meadow
#

I'm not asking, you are 😛

#

I'm telling you to read the docs, they're explaining everything

cosmic rain
royal wigeon
cosmic rain
#

Yes

royal wigeon
#

Thanks, for me reading complicated docs like that is kinda hard.

cosmic rain
#

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.

royal wigeon
cosmic rain
#

Platform referes to the device that they run the game on, i.e. windows PC, Linux, PS5, Android, etc...

dawn nebula
#

Got this code snippet. Anyone know where Delta.Multiply is from? Is that a Unity thing?

leaden ice
#

Not a Unity thing

dawn nebula
#

Well, hope the creator responds then.

gusty aurora
#

Probably just a negative exponential

#

v = v * (exp(- damp * dt))

dense estuary
dense estuary
#

You mean like, a variable is only visible in unity if?

heady iris
#

This won't change whether the field is serialized, but NaughtyAttributes provides an attribute that conditionally shows the field in the inspector

leaden ice
#

If you mean conditionally shown in inspector, then yes

#

conditionally serialized, no

heady iris
#

It's a third party asset.

leaden ice
#

editor plugin, yes

heady iris
#

It's the most practical way.

#

You could also write a custom editor.

leaden ice
#

Well you could write the custom property drawer the same way the plugin does

#

Unity Editor was made to be extensible

heady iris
#

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
faint hornet
#

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.

leaden ice
#

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);
}```
faint hornet
leaden ice
#

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

leaden ice
#

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

faint hornet
# leaden ice it's just a set of positions

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

leaden ice
#

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

fervent furnace
faint hornet
# leaden ice can ytou explain the use case more?

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

fervent furnace
#

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.

leaden ice
#

that feels like a better answer than mine!

faint hornet
leaden ice
#

Are you familiar with graph theory yet?

#

You'll really want to be, if you're making a tile based... anything game

faint hornet
dense tusk
#

sometimes all you need is to come back with a fresh set of eyes

faint hornet
cosmic rain
faint hornet
cosmic rain
#

4 tiles = 4 nodes

#

I don't see why they should be multiplied by 2

faint hornet
cosmic rain
#

So are you counting relationships or nodes?

#

Each node would have several relationships(edges), but the total count of nodes wouldn't change.

faint hornet
#

Both but can’t it be simplified to something like 4

cosmic rain
#

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.

fervent furnace
#

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

faint hornet
#

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?

faint hornet
cosmic rain
#

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?

faint hornet
cosmic rain
#

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.

faint hornet
#

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

faint hornet
faint hornet
cosmic rain
faint hornet
cosmic rain
faint hornet
cosmic rain
#

Comparing graphs might be tricky.

faint hornet
cosmic rain
#

Nope

faint hornet
#

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

▶ Play video
#

@cosmic rain

#

@cosmic rain did you see it at 36min?

cosmic rain
#

Or 2d arrays

spring creek
#

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

faint hornet
#

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

faint hornet
faint hornet
spring creek
cosmic rain
#

So they have an opposite rotation, but the same shape

faint hornet
cosmic rain
#

You'd need to iterate the nodes and rotate their position relative to the pivot point.

faint hornet
#

i will draw a small example very quickly..

spring creek
#

So... comparing grids seems exactly like how to do it..

faint hornet
#

look at this. so both shapes are the same as a "shape" but also relative to their "dot"

#

@cosmic rain @spring creek @leaden ice

cosmic rain
#

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.

faint hornet
#

save just the shape and its data related to the dot.

cosmic rain
#

Well, you'd need some way to isolate a shape into a separate grid

faint hornet
cosmic rain
#

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.

faint hornet
#

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

fervent furnace
#

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

faint hornet
#

i dont understand

cosmic rain
faint hornet
cosmic rain
#

The simplest solution is often the best solution

fervent furnace
#

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

faint hornet
fervent furnace
#

imagining the letters are inside a grid

faint hornet
fervent furnace
#

you can read my AABB solution.....should be slightly faster by filtering the AABB

faint hornet
faint hornet
fervent furnace
faint hornet
fervent furnace
#

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

faint hornet
#

0,0 1,0 2,0 1,1
B is pivot, then B +1, then B + 2, etc?

faint hornet
fervent furnace
#

(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)

faint hornet
faint hornet
fervent furnace
#

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

faint hornet
#

how to rotate this?

#

here without X's

AAAP
 A
----
P
A
A A
A```
fervent furnace
#

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

faint hornet
#

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)

faint hornet
fervent furnace
#

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

hollow escarp
#

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();
    }
}

}

spring creek
spring creek
cosmic rain
tawny elkBOT
cosmic rain
#

!ide

tawny elkBOT
quartz folio
cosmic rain
#

Ah I see you fixed the syntax error(was basing my reply on the screenshot in the advanced channel).

knotty sun
#

please do not cross post

autumn magnet
glossy wave
#

in ECS, how do I move an entity in its forward axis? LocalTransform.Translate is giving me trouble

glossy wave
cosmic rain
#

Judging by the coloring, Forward is probably a method, so you need to call it properly.

cosmic rain