#archived-code-general

1 messages · Page 367 of 1

west hamlet
#

Thank's , Didn't knew about that!

late lion
#

When we talk about the length of a vector, it's best to think of it as a line originating from the zero point. It's implicit, we don't store that origin point in the vector, that's just where vectors start from.

leaden ice
#

Normalization is the process of getting a _unit length _ (aka length == 1) vector in the same direction as a given vector

#

Vectors have a direction and a magnitude. A normalized vector always has a magnitude aka length of 1.

#

That's all it is

#

It is useful because 1 times anything is that number

#

So you can get a vector in the desired direction of any length you want by multiplying the normalized vector by the desired length

queen saffron
#

Hello everyone, is there a script or utility for subtracting faces ?

leaden ice
#

(sorry I was in a tunnel so my answer was slow)

humble shoal
cosmic rain
cosmic rain
#

What you can do is normalize it so that the length is equal to 1.

humble shoal
#

Ohhh

#

Thanks so much @cosmic rain @leaden ice @late lion @thick terrace @tired elk

leaden ice
knotty sun
#

please do not cross post

real spire
#

i apologize

knotty sun
real spire
#

thank you

versed loom
#

which version is more better? ( builder is stringBuilder )

builder
                .Insert(startIndex, '<')
                .Insert(startIndex + 1, styleTag)
                .Insert(startIndex + 2, '>');

            builder.Insert(startIndex, $"<{styleTag}>");```
leaden ice
#

Certainly the one with fewer Insert calls
Insert will likely be relatively slow compared to Add. It probably needs to shift all subsequent characters down in the array to make room.

#

also pretty sure the first example won't even work, since startIndex + 2 will not necessarily be correct if styleTag's length is greater than 1.

queen saffron
spare dome
queen saffron
#

not deleting.
wait i will make illustraction about it

spare dome
#

like a boolean modifer?

#

i believe probuilder can do that also

placid edge
#

I'm trying to reference things in a script variable through code, problem is the script is stored in a Component variable (It has to). Is there a way to convince a Component it is a Script?

#

as in trying to reference a script from another script

spare dome
placid edge
#

it has to be a Component

#

because the variable changes scripts all the time

spare dome
#

a script is a component so explain

knotty sun
queen saffron
placid edge
#

this is the variable. I'm trying to convince Component to let me use things like StopCoroutine

placid edge
queen saffron
knotty sun
spare dome
queen saffron
#

basically, upon a a main face subtracts a subface creates all the 8 new subfaces surrounds the subface

#

making the sum of the subfaces equal to original face

spare dome
#

so you want on the deletion of a face you want to create 8 new faces around it?

#

what are you trying to do exactly here

queen saffron
#

not deleting a face, all faces must remain but the original face will be divided into different smaller faces

spare dome
#

so subdividing

#

you could have just said that

#

yes i believe probuilder can do that

queen saffron
#

i recently implemented my own subdivision where the subdivision scripting for probuilder is not available

placid edge
#

is Monobehaviour another way of saying C# Script or is there more to it

queen saffron
#

Another illustration

knotty sun
spare dome
queen saffron
#

it is not available to use in a script right?

spare dome
#

im not sure ive never messed with it

queen saffron
#

thanks @spare dome for assistance!

spare swallow
#

Hey all! Just wondering if it's possible to natively create a fading out or "soft" shape in Unity? This example was created in photoshop but it represents the general idea I am looking to get, in my actual usecase I am looking to create a halfcircle following the same concept. Thanks!

lean sail
spare swallow
thick terrace
#

like just as a Texture2D or...?

#

just to get this out the way, why can't you cut the one you have there in half in photoshop? 😛

spare swallow
indigo tree
spare swallow
thick terrace
#

maybe just make one big enough for the largest size you need to support? if it's a simple gradient it only needs one channel so it shouldn't be that big

spare swallow
thick terrace
#

it woudln't be difficult to create a texture dynamically for that but there's nothing built in, you would just need to create a texture and set the pixels youself

spare swallow
indigo tree
#

Just have an alpha gradient

thick terrace
spare swallow
indigo tree
#

Procedural shapes.

spare swallow
spare swallow
indigo tree
#

Oh, if it is a fixed aspect ratio svg format may be a good idea. IDK how well they translate into unity though

spare swallow
#

I can't seem to find any documentation natively either, is it a package?

spare swallow
#

supposedly they are compatible with UI Toolkit, so I'll have a look into that.

indigo tree
#

I’m not sure if it does or how well it does it

indigo tree
spare swallow
trim schooner
spare swallow
oak seal
#

hi!

#

im havin' problems with

#

a shader

#

it cuts itself off cause i enabled ZWrite to fix another problem

#

shader thing btw

lean sail
oak seal
lofty pawn
rigid island
#

check if you have clear flags set to Solid Color

lofty pawn
#

No way!

#

Thank you so much

#

I would have never thought it was because of the camera settings😅

sour wasp
#

can anyone help me figure out how i can detect if i'm hovering over a unity transform handle? i made a scene GUI listener for selecting objects in my custom world system, but i can't drag the transform handles because i have to call Event.Use() if the cursor is hovering on a world object, so clicking on the handles just selects my objects

#

this is the code for reference

dense tree
#

hey everyone! im working on a top down space shooter type game with really floaty controls. i want to create a dash mechanic, but using rb.Addforce just doesnt feel responsive sometimes, any fixes?

maiden fractal
tawny elkBOT
dense tree
#
if(Input.GetKeyDown(KeyCode.W))
{
    timeSinceLastW = Time.time - lastWTime;
    if(timeSinceLastW <= doubleInputTime && canDash==true)
    {
        rb.AddForce(Vector2.up * dashSpeed * Time.deltaTime);
        StartCoroutine(DashCooldown());
    }
    lastWTime = Time.time;
}
if (Input.GetKeyDown(KeyCode.S))
{
    timeSinceLastS = Time.time - lastSTime;
    if (timeSinceLastS <= doubleInputTime && canDash == true)
    {
        rb.AddForce(Vector2.down * dashSpeed * Time.deltaTime);
        StartCoroutine(DashCooldown());
    }
    lastSTime = Time.time;
}
if (Input.GetKeyDown(KeyCode.A))
{
    timeSinceLastA = Time.time - lastATime;
    if (timeSinceLastA <= doubleInputTime && canDash == true)
    {
        rb.AddForce(Vector2.left * dashSpeed * Time.deltaTime);
        StartCoroutine(DashCooldown());
    }
    lastATime = Time.time;
}
if (Input.GetKeyDown(KeyCode.D))
{
    timeSinceLastD = Time.time - lastDTime;
    if (timeSinceLastD <= doubleInputTime && canDash == true)
    {
        rb.AddForce(Vector2.right * dashSpeed * Time.deltaTime);
        StartCoroutine(DashCooldown());
    }
    lastDTime = Time.time;
}``` This is all in the update function
#

here is the coroutine

IEnumerator DashCooldown()
{
    canDash = false;
    yield return new WaitForSeconds(dashCooldown);
    canDash = true;
}
spare dome
knotty sun
dense tree
#

okay i can do both of that, it was pretty late when i wrote that so i must have been zoned out or something hehe

rigid island
#

dont use Time.deltaTime on addforce, thats why its messedup too. Also would go with Impulse mode instead if you need one frame

spare dome
knotty sun
spare dome
#

instead of several times

#

its pretty common

dense tree
#

im not following

#

what is this movedirection

spare dome
#

X and Y are inputs

#

via getaxisraw

dense tree
#

ahh i see, what are orientation.up and right?, are they 0 and 1 values?

spare dome
#

no they are the direction(s) of your player

#

just change orientation to Player

#

or whatever transform you have

dense tree
#

okay, but thats only for the efficiency of the code right? this wouldnt change how the dash would work. i removed the Time.deltaTime multiplications and put this code into FixedUpdate and now the dash is even more inconsistent :/

spare dome
#

if you put the inputs in FixedUpdate() it will act a little wierd

dense tree
#

hmm, so i how would i call the rb.Addforce in FixedUpdate() from the if statement in update()?

#

maybe i could do that using booleans?

spare dome
#

well if you use the Movedirection you can just do RB.addforce(MoveDirection * Speed, Forcemode.Force)

#

and thats it

#

pretty much

dense tree
#

alright, so i use GetKeyDown for the double input checking, then i use GetAxisRaw to check which direction im going, and apply the force in that direction?

#

and MoveDirection is a vector2 value?

spare dome
#

X and Y are inputs and produce a 1, 0 or -1

dense tree
#

mhm, then what about the timer?

#

yeah

spare dome
dense tree
#

is my timer not working around GetKeyDown for the second input within the timeframe?

spare dome
#

you can just put the timer around the movedirection if you want

#

i havent use double tapping inputs in a while

dense tree
#

i think using getkeydown wouldnt hurt no

spare dome
# dense tree i think using getkeydown wouldnt hurt no

you could probably just do

if (X)
{
    timeSinceLastD = Time.time - lastDTime;
    if (timeSinceLastD <= doubleInputTime && canDash == true)
    {
        Timer = true;
        StartCoroutine(DashCooldown());
    }
    else
    {
        Timer = false;
    }
    lastDTime = Time.time;
}
#

something like this

#

you would have to mess around with it

dense tree
#

hmmm yeah thats pretty much it but condensed

#

unrelated question, but is there like a trigger system for just code, like there is in animations?

merry stream
#

I'm trying to make a procedural passive skill tree for my game and am running into some issues with constructing a possible tree with no overlaps (currently just having them connected in 4 directions (up down left right). I'm currently doing this iteratively but its a not working so well especially when there are "branching" nodes that have more than one connection. I feel like this could be solved much easier with backtracking/recursion but i'm not exactly sure how to do it. Any sugessions?

spare dome
#

if thats what you are looking for

dense tree
#

hmm, maybe just switching to your movedirection method would be easier

#

how would that look like? if you dont mind can you sort of write a bit of it

#

i dont wanna just copy paste im genuinely interested

spare dome
dense tree
#

oh shit my bad

#

thank you hehe

dense tree
#

nevermind that wasnt too hard

spare dome
#

and i showed you how to implement it into addforce()

dense tree
#

oh like its rotation?

spare dome
#

no

#

movedirection is a vector3

#

which is a positon or a value

dense tree
#

is orientation a variable name or a built in function?

dense tree
spare dome
#

orientation is a transform which is a variable

#

all it is, is a transform of your player

dense tree
#

alright, thank you!

spare dome
#

cool beans

somber nacelle
#

fun fact, but AddRelativeForce exists so you don't need to use the transform to multiply the individual axes to get the world space direction of force. just pass the local space direction to AddRelativeForce and it does the work for you

manic pagoda
#

How can I make rotation smooth?

dense tree
#

man im still stuck, i cant figure out how to check for double inputs using GetAxisRaw

dense tree
#

like double taps

spare dome
dense tree
#

man im forgetful

#

but like then even if i press A then i press S, it would dash down

#

that doesnt ensure the same button is being pressed

spare dome
#

i updated it

#

that should do it

#

all getaxisraw is, is an input

#

it acts like W A S D

hallow portal
#

hey guys i wanted to make my player a prefab(for clclasses) but now i dont know how i make my inventory work bc i cant asign anything does any1 know something? https://hastebin.com/share/ejetodofaf.csharp

dense tree
#

but getaxisraw checks for inputs every frame no?

lean sail
spare dome
hallow portal
dense tree
#

unlike getkeydown

hallow portal
spare dome
#

i might have to dig to find mine

manic pagoda
lean sail
# hallow portal and i am sorry i am a beginner what do you mean with instantiate it and making i...

This should definitely be in #💻┃code-beginner then. But regardless if you have a prefab you need to instantiate it so it exists in the scene. Look up the method Instantiate and try it out.
Prefabs can reference other prefabs, so some of those objects you're trying to reference might be fine to turn into prefabs as well. Otherwise youd need to assign the value in a different way, like at runtime.

manic pagoda
river kelp
#

I reinstalled Unity on a new computer recently, and everything seems to be working fine except I have to regenerate project files every time I create a new script file or Visual Studio bugs out.
Specifically, the new file I created will be present in the solution explorer but won't be able to find any dll files including System or Unity itself.

Is there a checkbox I forgot to press or something? Or is this an issue someone else has had too? I'm on LTS 2022.3.43f1 using Visual Studio Community 2022

#

(Regenerate project files resolves my issue, but only temporarily as I will have to do it again once I create a new file)

leaden ice
#

Is your visual studio package in Unity up to date?

river kelp
#

Well, there is no "Update" button available in the package manager, the version says it was released October 11th 2023 though

#

My install is like, one week old

#

The visual studio package is on version 2.0.22

river kelp
elder zenith
#

Hey, what's generally regarded as the best solution for getting a class from a collision target?

'Cause I can think of 3 ways, two of them seem like bad practice.

  1. Use tags. Just probably a bad solution overall considering how clunky tags are.

  2. Use TryGetComponent<>(). From what I understand this is horrible when it comes to performance.

  3. Write a manager class that objects of a class register to OnEnable, then handle the collision checks in there. This seems like the most logical solution, but I feel like writing something that would be performant would be difficult, and wasteful, as Unity built the entire 2d collision system for this exact reason.

river kelp
#

Just use getcomponent

#

well, not to check what kind of object it is maybe. If you want to test the object for type then tags seem to be the accepted solution

elder zenith
#

You can't have multiple types of tags on an object though, can you? And it's very prone to typos

leaden ice
#

TryGetComponent is completely fine

#

Nothing wrong with it from a performance perspective

#

That's the best solution IMO

river kelp
#

Yeah like it's not the absolute cheapest function in the world but

#

it's very unlikely that will be the thing that slows you down

#

unless you're having thousands of these all the time

leaden ice
#

I'd dare you to even find the impact of TryGetComponent in the profiler. It's fast.

#

This also gets you directly to the data you will need, rather than requiring a subsequent call

elder zenith
#

If I'm making a Projectile class for example, and an enemy that shoots 10 bullets at a time, having each of them ( x however many enemies you have on screen) run TryGetComponent() every frame seems... suboptimal?

river kelp
#

It's fine

river kelp
#

the 10 bullets aren't colliding with every enemy on screen every frame

leaden ice
#

If you're really dealing with thousands of objects on screen at once you should probably be looking into ECS anyway.

elder zenith
#

...huh fair enough. I was really convinced it's a bad solution 😅

river kelp
#

Touhou levels of bullets should be fine though

river kelp
elder zenith
#

Thanks you two!

indigo tree
#

Running TryGetComponent that is

elder zenith
#

To make entities take damage.

#

Currently just have a Damageable class that holds HP and an event OnHit

indigo tree
#

More of a organization thing than a performance thing

#

Though if you are making a touhou clone 100% manage dependencies some other way lol

leaden ice
#

It's unclear exactly what alternative you're proposing

#

The physics engine is faster than almost anything you would write.

indigo tree
leaden ice
#

We're talking about Raycasts

#

Which give us colliders

#

And the way to go from a collider to data associated with the Collider (I e. Another component) is to use GetComponent

#

Outside of that you'd be talking about your own home grown physics queries or something, or some other way to associate data with GameObjects... a dictionary? Which doesn't seem like it'd be any faster or easier

latent latch
#

I don't really use them much, but I assume Unity tag comparison could be quicker, but I guess you still need a component look up anyway?

#

Also, I've not looked much into it, but does the component search linearly or is it all hashed

leaden ice
#

I've never been convinced by CompareTag being somehow faster than TryGetComponent. Doesn't CompareTag have to iterate over the whole tag to check for equality between the tags?

#

Is that really faster than comparing the class type pointers? And iterating over a similar or smaller number of things

#

HashCode() for a string iterates the whole string afaik, unless it's cached.

latent latch
#

Honestly, it's all probably a micro-optimization anyway, and doing GetComponents each frame (even multiples) is pretty common

leaden ice
#

Indeed

indigo tree
leaden ice
#

We're starting from a Raycast

river kelp
#

Is there some rule against installing Unity on the D drive or something

leaden ice
#

Now you need to get the data about the thing you hit

#

And you're suggesting against using GetComponent

river kelp
#

like, does the main unity install only work on C?

open plover
leaden ice
#

So I'm trying to figure out your alternative

indigo tree
river kelp
#

my cache?

indigo tree
#

Yes

river kelp
#

I'm not sure what cache you're referring to

indigo tree
#

Like your lightmap baking and stuff

river kelp
#

oh, sure

#

I'm being told visual studio can't find any of my references, but when I look in the project file and check the path the references lead to, I find the dll

#

Reinstalling Visual Studio, deleting the library folder, etc doesn't fix it.

river kelp
#

Closing and re-opening visual studio fixes it until I do something else that disturbs the fickle VS gods

river kelp
broken light
#

managed to fix it in the end

river kelp
#

Please, it's been killing my flow for a week now

#

What was your solution?

broken light
#

second let me check how i did it

#

clear your project in preferences, like you normally do and i deleted the relevant folders so it will properly regenerate, then i closed unity and re-opened. Then instead of double click scripts to open VS i instead linked it via assets > open c# project

#

that seemed to properly link vs to unity

#

after that i could once again double click open links

#

im also making sure unity is on latest version of unity 6 and vs is also updated

river kelp
#

Hm, what did you delete to make the project file regenerate?

broken light
#

library i think

river kelp
#

Is it safe to delete the project file itself?

#

the csproj file, the solution and such

broken light
#

not sure but i didnt delete that

river kelp
#

I've deleted the library, regenerating only temporarily fixes the issue as it immediately happens again when I make a new file

#

using the assets - open c# project did not help

#

I can double click to open files though, my issue is just that the csproject loses the references

#

It's almost like the project file itself ceases to exist

#

Like, the project file was deleted and replaced with a new one, but visual studio still remembers the old file which it can no longer read

river kelp
#

Huh. Adding the "player project" to the list of projects to generate fixed it. If anyone else has similar issues try that

#

I don't know what that project does, but as long as it doesn't break my flow I'm happy

spark flower
#

Hey guys, so i have this class which spawns another class setting a variable in it called "radius", also in this class if it collides with a certain object, it creates an instance of itself without setting the variable "radius". problem is, the variable "radius" is set to whatever it is set in the original class that spawns it. i will share screenshots, hopefully it is clear.
1st screenshot is in spawner class.
2nd screenshot is in the ripple class.
-notice that .Setup() is called only from the spawner class, and not ripple class. but radius is set to spawner class on all ripples regardless.

#

radius in spawner class is set to 5, in ripple class is set to 1

#

i mean in the prefabs

#

but all ripples get spawned with radius of 5, the spawner, regardless.

#

and i dont know why is that

dusk apex
#

The clones would then have the same data as the cloned object.

spark flower
#

so i guess thats why?

dusk apex
# spark flower so i guess thats why?

A workaround (without having to change too much of your current setup) would be to cache the spawned instance and set it's prefab to the asset prefabcs var ripple = Instantiate(rippplePrefab, ... ripple.ripplePrefab = rippplePrefab;Referencing from the inspector would reference itself, unfortunately - useful in itself but not for your case.

spark flower
#

I see, thanks

earnest cobalt
#

Hello! So quick thing, im having issues and IDK if the issue its on my health system or bullet system, my guess is on the bullet system since I tried to get a hit confirmation on the debug logger but im unable to make it work, so first pic is going to be the health sys and the second the bullet one if anyone can help me with any insight (I really dont understand c#)

spare dome
#

im guessing you are getting some

earnest cobalt
#

So the health system is working as intended but the bullets bounce on the dummy and dont remove from his pool of health

spare dome
#

i mean what errors are you getting

#

in the console

earnest cobalt
#

The console doesnt give any errors

#

I tried using the debug.log to get to see if the bullet was working but it haves no effect I can share screen if you wanna see

spare dome
earnest cobalt
spare dome
#

so you must write the code with the correct capitilization

earnest cobalt
#

Like this?

spare dome
#

yes

earnest cobalt
#

Yes

#

Its working

spare dome
#

i would suggest !learning unity to fix this next time

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

earnest cobalt
#

Why tho? It wasnt collecting the health component from the collision object?

spare dome
#

but you need to get the health script from collision

#

you could use a try catch next time to debug if needed

earnest cobalt
earnest cobalt
spare dome
#

it will try something, if it cannot do such thing it will throw an error

earnest cobalt
#

Thanks! This actually helps me a lot, Im trying to make sense of a lot of this, but it all looks like rune language to me so im trying the best I can, thank you @spare dome

spare dome
tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

spare dome
#

come back any time for help!

worn crystal
#

so just need some help regarding conceptualizing what im thinking of, im working on a card game atm and trying to create a pseudo-statemachine? i dont think im 100% following the pattern to make it work with my situation but wondering if theres a better way i can handle this

#

the state machine itself has some state transitions, but from what i understand you dont usually inject states with data?

#

for example, lets say im in some state and i want to do a "draw card action", i dont necessarily need to do a state transition to draw a card, but i want to update the current state and its relevant information with the additional cards

#

am i conceptualizing this wrong?

latent latch
#

what are these states

worn crystal
#

specifically:

  • start game/init
  • draw mana
  • draw card from deck
  • player turn

then during the player turn, they decide they want to draw a card lets say, it doesnt really make sense to make it a state here right?

#

because theyd draw the card but it would still be the player's turn

#

unless you think maybe i should make it something like a state where its only function is to draw a card, then it immediately transitions back to the previous state?

latent latch
#

I'd handle it with a sequence of logic like methods such as:
BeforeDrawPhase()
AfterDrawPhase()
BeforeCombatPhase()
AfterCombatPhase()

worn crystal
#

oh sorry, i meant the draw happens after player turn

#

so it would look more like:

  • player turn
  • they decide to draw a card as an action
  • still the same players turn
latent latch
#

Good example of a state would be clicking a card and figuring out if the player can play it or not when invoking IPointerHandler

#

If(Player.state == Phase.CombatPhase):
//play card

worn crystal
#

also for some extra info, my state machine has the normal Enter/Exit methods, but it also has an additional method called "TryGameStateAction" which passes some eventargs, and in some cases it might queue the next state, modify the current state, etc

#

ignore the boolean, but example here

latent latch
#

Games like Yugioh it's probably a bit more complex with states, but something like SlayTheSpire is very linear in how state logic works

worn crystal
#

definitely a bit closer to yugioh than slay the spire

#

based on cards certain actions might be possible or not for example, card effects can be activated, etc

latent latch
#

Still, I think states would be indentical to how phases work in yugioh.

#

You got the draw phase, the battle phase, the after battle phase

worn crystal
#

true

latent latch
#

I'd imagine it's a total mess for how those games are coded.

#

there's just so much extra stuff to keep track of for when you have some complicated effect in place

worn crystal
#

yup lol, there actually is a unity game of the card game im trying to make right now and i decompiled the code to take a look, total mess lol

#

game logic script had like 15k lines of code

#

seeing if i can create it without making a total mess

latent latch
#

I'd structure it more and make a rule set for the ordering of effects

worn crystal
#

pretty much what im looking to do

#

i guess my difficulty is lying in the fact that some actions dont cause the game state to transition but some game state data to still update?

#

but i guess even the action of "drawing a card" can be a state in its own then i immediately transition back to the battle phase

latent latch
#

drawing a card would be similar to my method above:
BeforePlayerTurnPhase()
{
//Draw Card
}

worn crystal
#

yeah but its a player action, so the player has the choice to draw or not

latent latch
#

Ok so that would be during the phase then

worn crystal
#

exactly

latent latch
#

If that doesn't advance the phase, you just flip a bool or create another substate of sequences

worn crystal
#

wdym by create another substate of sequences?

latent latch
#

Probably give me more of an idea what would happen if a player draws or not

worn crystal
#

we are in the player action phase => some game state data gets updated so that the player has an extra card in hand => still their turn
we are in the player action phase => player doesnt draw => still their turn

#

if they draw or dont draw the resulting state is still the same

latent latch
#

Right, so you're just awaiting for the player to confirm, but ultimately nothing in the state changes (that would otherwise cause split logic)

#

so IPointerHandler callback or w/e input method will be what advances it

#

as for something like substates, you can do another handful of states/enum for each specific phase

worn crystal
#

for the state machine pattern btw, there usually isnt persistent data between states right?

latent latch
#

PlayerStatePhase has substates of DrawingCard, BeforeDrawEnd, ect

#

well, usually you do have flags that would persist.

worn crystal
#

yeah that makes sense

latent latch
#

Not everything needs to be a state as sometimes you just need some bool to compare against in other phases

worn crystal
#

makes sense

#

hmm alright, i think i have a decent idea of what to try now too? makes things a bit complex since actions can be optional but i think i can manage something?

latent latch
#

I've only made like SlayTheSpire type games where all the logic is very linear but I've probably got some ideas

worn crystal
#

its not a very linear game unfortunately lol so im definitely not able to stick to the design pattern 100% but im modifying it where it matters hopefully

latent latch
#

I'd totally keep TRAPS and stuff like that very generalized. Don't have 10 types which can be activated in specific phases

#

spells can only be played in like battle phase, ect

worn crystal
#

oh unfortunately there are some cards that can be activated in different phases lol

#

example, theres cards that can be played during your turn or during the "counter" phase

#

but i think i have a solution for that at least

latent latch
#

Right, I'm saying that try to keep a generalized amount of requirements. WhenEnemyMonsterIsPlayed, WhenPlayerTurnEnds, WhenEnemyMonsterDies

worn crystal
#

ahh, yeah of course

latent latch
#

no yugioh BS like if monster is 1000 hp and you have half life total and there's a solar eclipse

worn crystal
#

i wont be making one off methods and things like that

#

very much will be generalizing requirements, plan on making some editor scripts to make those things easier for card effects and all

calm mountain
#

Is there a limit to how many items I can initialize in a list through the inspector

#

I'll likely max out at like 200

#

So if that's not an issue then I'm squared away

cosmic rain
calm mountain
icy depot
#

i'm at a loss

dusk apex
icy depot
#

oh what

#

is that why

dusk apex
#

4f/5f

icy depot
#

weird, but thanks!

#

i hope it works this time

lean sail
# icy depot weird, but thanks!

that is how int division works. 4/5 is 0, the values are truncated meaning the decimal is dropped.
4/5 = 0
0 * anything = 0

#

by using floats you keep the decimal

icy depot
#

i always assumed it knew when to switch to float, but I guess ill have to use 'f'. Thanks!

analog dome
#

Hello, does anyone know why the Unity DevOps isn't working, I set everything up correctly, but the other person can't add the UVCS repository in the unity hub

outer plinth
#

Hello, wondering if someone could help me with what should probably be a very simple fix - In the following code when a TransformPoint moves the newRPos isn't updated and the offset applied is wrong in MoveInitialRoundingPoints()

I can see that the amount it's incorrectly offset by is equal to the distance travelled when the TransformPoint is moved, so I need to be able to update newRPos when the TransformPoint moves, but this causes unexpected behaviour because I think it's being updated whilst it is moving.

Any suggestions?

https://pastebin.com/c44MTngG

leaden ice
#

Or at least point it out

#

It's also not clear what you mean by TransformPoint moving

outer plinth
knotty sun
outer plinth
#

yep that's no worries, I know exactly what's happening and how much the offset is incorrectly by, and even where it's happening so it shouldn't bee too difficult to figure out

hallow portal
#

does some1 know how to make a inventory if your player is a prefab?

#

like ways to do it with the asigning adn stuff

cosmic rain
cosmic rain
#

The simplest form is an array of items or ids of the items.

hallow portal
cosmic rain
#

Wdym by "not for"?

#

this is how you can implement an inventory

#

If that's not what you're asking, then clarify the question

hallow portal
hallow portal
cosmic rain
hallow portal
#

i think the second is more simple so i think just making an empty object with a seprate script that asigns the slots?

hallow portal
cosmic rain
cosmic rain
hallow portal
cosmic rain
cosmic rain
#

No

#

Maybe expain what you're trying to do first

#

Are you trying to populate the inventory with the initial items? Or give the items on certain events in the game?

hallow portal
#

what i am trying is that when the player spawns in he has the inventory

#

but i cant asign the slots

cosmic rain
hallow portal
#

you get a type mismatch

cosmic rain
#

If it doesn't work as you expect, you'll need to clarify

hallow portal
#

so you cant

cosmic rain
hallow portal
#

do you have unity open?

cosmic rain
#

You'll need to clarify and provide details

cosmic rain
hallow portal
#

but if you ahve a item in the scene and you have a prefab you cant asign the item in the scene to the prefab

cosmic rain
#

That you definitely can't. Why are your items in the scene?

hallow portal
#

the canvas for the inv

#

those are the items in this case

cosmic rain
#

Items should just be data. An SO or even just a plain C# class/struct. They ui icons, or whatever you're referring to, would need to be updated at runtime with the data from the player inventory.

#

You're doing something very wrong if your actual item data and logic are part of the canvas

hallow portal
#

i mean this is on the player

#

i cant asign anything

#

bc player is a prefab

cosmic rain
#

You can assign prefabs/SOs/other assets or even define the item data right in the prefab.

#

The only thing you can't do is reference objects in the scene

#

What type is InventorySlots?

hallow portal
#

image

#

or you mean in the code?

cosmic rain
#

Both. There's no difference between the type in code and in the inspector

cosmic rain
#

Besides, an Image is a ui component. It's not even a texture/sprite.

hallow portal
#

i am not trying to asign the items just the inventory it self

cosmic rain
#

Ok, I think I get it. All this time you were asking about inventory ui and not an inventory system. Is that correct?

#

And how to bind it to the character actual inventory

hallow portal
#

yep

cosmic rain
#

Ok, you should make your intention clear from the very start.

But anyways, you can bind your character inventory to the ui when the character is instantiated.

#

Then your ui would need to iterate the character items and generate icons for them in the correct ui slots.

hallow portal
#

you can bind your character inventory. this is my whole question

#

howww?

cosmic rain
#

inventoryUIManager.Bind(character.Inventory)

hallow portal
#

thanks i will try this

cosmic rain
#

Just in case: that line alone wouldn't work. You need to implement it.

hallow portal
#

okey

trim thistle
#

Guys, please tell me how to create an inventory. I don't understand anything from these tutorials on YouTube; they all use the same template. But I want to understand how to create an inventory where there are objects of different types with various parameters, even if they are the same object. How do you display this on the view and how do you save everything, including both the order on the view and the objects themselves?

cosmic rain
upper pilot
#

Is there a way to have onvalue changed in the inspector for toggle to accept parameters other than bool?

#

I want to set which gameObject will activate when a toggle is On from the inspector, or is that not possible?

#
    public void OpenTabContent(GameObject content)
    {
        previousContent?.SetActive(false);
        previousContent = content;
        content.SetActive(true);
    }
trim thistle
hallow portal
#

@trim thistle can i msg you i have a good tut

cosmic rain
cosmic rain
cosmic rain
indigo tree
# trim thistle Guys, please tell me how to create an inventory. I don't understand anything fro...

How to have objects of various types and different parameters? Well, you’d have all of the items either derive from an abstract class or interface that allows them to be stored and accessed in the inventory. They’ll have to be stored in a collection, likely a list but if you have specific slots a matrix may be better.

How to display the items? Iterate through each inventory item at get the information about the display before adding it to the screen. This step largely is based on your framework, but for Ui you can instantiate items into a layout group and set their texture to the item’s texture.

How do you save everything? This really largely depends on the dats structure of the items. You would probably use binary or json serialization to write a file. Just note that the default unity serializer is a bit limited

hallow portal
# trim thistle Can you tell me how to start building an inventory system correctly to support a...

https://www.youtube.com/watch?v=5l2D6xtZIgk this is a good 1 and a good series

Support the Channel!
https://www.buymeacoffee.com/HawkesByte

Hello to all new and old, I'd be surprised to see if anyone still remembers this channel but I'm back with something a little different! A common question I would get when I was still developing my survival game was how the inventory system worked and if I could make a tutorial, and ...

▶ Play video
latent latch
#

inventories are fun

spare swallow
#

Sorry this isn't the right channel haha, I'll move it sorry!

vagrant blade
#

(But also, you have to make your shader transparent)

spare swallow
#

Had to connect my "Sample Texture 2D" to the new alpha channel created, appreciate the help!

cyan musk
#

So I’m trying to use a flood fill algorithm on a texture generated during runtime to add color variation and what not I have the basic set up I want but simply don’t like the way it looks it generates circular is there a way to add ig noise to it or random variables so it can spread in different directions

leaden ice
fierce vigil
#

Hey so I don’t have time to show the code or open unity because I’m at work. But what is the best way to understand code you want to reapply in your own project

quaint rock
hexed pecan
#

Yeah. Dont proceed until you understand

fierce vigil
#

I mean I kinda understand but how do you start by making it in your own project. I doubt copy and paste is a good idea

quaint rock
#

if you know how it works and why it works and know how your project works should be able to adapt

steady moat
queen saffron
#

Hello i am having code existential crisis where my test run works perfect but upon testing on a mesh model it buggs out

#

the goal is to 'subdivide' faces based on a given subface and create the 9 subfaces that combined together makes the main face (no overlapping)

steady moat
#

Maybe you have issue if vertices are shared

#

Or maybe you have issue depending on your object bounds/space.

queen saffron
#

sry but i don't get your intention

steady moat
#

You have a square which is not a cube.

queen saffron
#

i don't affiliate myself with sharedvertex or other properities in probuilder.

what i do in my project (cube) is obtaining the closet face i'm clicking on and preview shows subface being made. the main face (top face of cube) has been chosen without mistakes nor creating a subface. But, idk for some reasons it is not working as it should be.

steady moat
#

You clearly shown a mesh that is being cut. If it was working in a test example such as having (A single face), it is mostly not working because a cube is not the same as a single face.

quaint rock
#

import a cube from a dcc package that way you can ensure it is made correctly for your purposes and rule out how hte mesh is made

#

since you can ensure there are no shared vertices

steady moat
#

You can have share vertices, and the position of the vertices will not be the same (same if you take a single face) the your test case.

#

Programmation is not magic. (At least, in your case)

queen saffron
#

// Get the final rectangle vertices
Vector3[] rectangleVertices = new Vector3[4];
for (int i = 0; i < 4; i++)
{
    rectangleVertices[i] = lineRenderer.GetPosition(i);
    rectangleVertices[i].y = 1.0f; // Ensure the rectangle is on the same plane as the mesh
}

// Add vertices to the mesh
List<Vector3> vertices = pbMesh.positions.ToList();
List<Face> faces = pbMesh.faces.ToList();


int[] vertexIndices = new int[] { 0, 1, 2, 2, 3, 0 };


for (int i = 0;i < vertexIndices.Length; i++)
{
    vertexIndices[i] += vertices.Count; //offset the indices
}

Face newFace = new Face(vertexIndices);

vertices.AddRange(sortedVertices);
faces.Add(newFace);

pbMesh.positions = vertices;
pbMesh.faces = faces;


//subtract the face creating 9 new faces and remove the main face aftwards
FaceSubtraction faceSubtraction = new FaceSubtraction(vertices, faces);
faceSubtraction.SubtractFace(pbMesh, closestFace, newFace);
steady moat
#

And as I said, those are only possible factors. It does not mean that in your case it is an issue.

#

I'm just pointing out that by building your test case of a single plane (that from what I understood was working) towards a Cube, you are mostly going to find the issue.

modern creek
#

When there's two scenes active, how do I control the UGUI draw order of elements in different scenes?

I have a UI element (in one scene) that's appearing above another element (in the other scene).

leaden ice
modern creek
#

they each have a canvas.. is there a canvas draw order?

leaden ice
#

Which render mode are the canvases using?

modern creek
#

screen space - overlay

leaden ice
#

Yes - sorting layer and order in layer

modern creek
#

gotcha, found it, thanks

#

hm... can UGUI elements override this sort order somehow?

leaden ice
#

Or is it greyed out for Overlay? If it's greyed out then it's just hierarchy order

modern creek
#

I have these two canvases, one's got a sort order of 1, the other a sort order of 5.. but an element in 1 is somehow appearing over elements in 5

leaden ice
modern creek
#

ooooooooh one canvas is overlay, one is screen.. hm

leaden ice
#

Yeah in that case the overlay one will always be on top IIRC

#

overlay draws after all cameras

modern creek
#

hm.. ok, that seems to make sense.. this is gonna be a tricky bug to figure out

queen saffron
#

Given a face of a mesh, is there a method to distinguish if the current face is clockwise or anti-clockwise?

leaden ice
#

Unity actually only uses triangles

#

and all triangles are clockwise

golden garnet
#

Hey! Is there a way to move the mouse with a joystick while using the Unity Old Input System?

#

I know there's WarpPosition but i'm not sure how to work that while using the old input

leaden ice
golden garnet
#

Dang, that stinks. virtual cursor seems like a bunch more work too.

leaden ice
#

which is the best option

golden garnet
#

I do like the new system and am decently familiar with it, but sadly for the purposes of this project it wouldn't be reasonable to switch.

#

I'm in too deep lol

leaden ice
#

¯_(ツ)_/¯

#

You have to weigh that cost vs the cost of implementing something with the old system

golden garnet
#

Oh well, thanks for the heads-up anyway!

leaden ice
#

There's always the "both" option

golden garnet
#

You mean both new and old input systems?

leaden ice
#

Yes.

golden garnet
#

Oof, seems like it would be a headache. Wouldn't it cause incompatibility when old input code is trying to run even though its obsolete?

leaden ice
#

What kind of incompatibility?

#

The main cost is performance - you'll be running both systems.

#

And the fact that half your code will use one and some will use the other.

golden garnet
#

Woah i did not know they allowed both at once

#

cool.

spare dome
#

i mean a ton of people have the old input system implemented still

#

so they kinda have to

golden garnet
#

I prolly will still just stick with old for now unless I get super desparate lol, I appreciate the advice tho

gray rover
#

Hey guys, I am taking the leap to trying to code my first multiplayer game and am coming across some challenges I cant find solutions to (or solutions that seem like spaghetti)

Here is the scenario, I have a host and a client that can connect to each other and everything is working great. I want to spawn an enemy for both players, typically in a single player game I have only 1 prefab for enemies and 1 scriptable object to define traits for the enemy and map them to the prefab when the enemy is spawned. However, for networking this it seems more complicated but I have figured out to be the basics, I still have 1 enemy prefab and 1 scriptable object and have figured out how to map all the network variables from the SO to the prefab except for the sprite since there is no network variable for sprites.. So currently I can spawn an enemy for all clients and the 3 network variables i have defined are being shared properly, I just need to figure out how to get the sprites to propagate to the clients.. here is some of the code

I tried adding this to the spawn enemies function with it only working on the host and the clients not seeing the change.
enemy.GetComponent<Enemy>().ConfigureEntity(enemy.GetComponent<Enemy>().entitySO.sprite);

I thought about trying to use a client rpc to propagate the change for the sprite however any client connecting after the rpc would not see the sprite.

Any insight would be much appreciated.

leaden ice
#

basically - give each entity an ID

#

and come up with a lightweight system for looking them up by that ID

#

so the client can do so based on a simple identifier

gray rover
# leaden ice I would probably use a NetworkVariable with either an int, an enum, or a string,...

Ok, so are you suggesting to store all of my enemySO in some sort of data container then pass the id of the specific enemySO in that data container to the clients and have them update the prefab information themselves? If this is the case, the server would configure all of the network variables that are housed in the enemySO and the client would only need to update non network variable information themselves?

leaden ice
gray rover
dusky elbow
#

Hi guys! I have been working on integrating an Unity XR app into react native based IOS app and it works but when I close unity using unloadApplication and then put app in background, it crashes with the following stack trace, happens on iPAD (works fine on iPhone)

honest osprey
#

Hi! im trying to render my shader (which i made with shader graph) to a texture. this is my current implementation, and im my head makes sense, added comments to help show my process

public RenderTexture rt;
public Shader shader;
Material mat;
MeshRenderer mr;

// Start is called before the first frame update
void Start()
{
    mr = GetComponent<MeshRenderer>();
    mat = new Material(shader);
    mr.material = mat;
    mat.SetTexture("_MainTex", rt);
    mat.SetFloat("_stps", 6.3f);
}
void savePic()
{
    // create rt and tex
    RenderTexture finalRenderTexture = new RenderTexture(rt.width, rt.height, 0);
    Texture2D tex = new Texture2D(rt.height, rt.width, TextureFormat.ARGB32, false);
    // take the base render texture that has what we see, then apply that to the finalRenderTexture with the shader materia
    Graphics.Blit(rt, finalRenderTexture, mat);

    RenderTexture.active = finalRenderTexture;



    // read in whats in the renderTexture and save that to tex
    tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
    tex.Apply();


    // save tex as a png
    byte[] bytes = tex.EncodeToPNG();
    File.WriteAllBytes(Application.dataPath + Convert.ToString(DateTimeOffset.UtcNow.ToUnixTimeSeconds()) + ".png", bytes);



    RenderTexture.active = null; 
    finalRenderTexture.Release();
   





}

the problem im getting is that it saves the texture out as a black images so i assume something is not been set right somewhere.
Thanks!

#

note i've removed the update method where i am calling savePic, character limit got me

cosmic rain
honest osprey
#

Yes, it's got a camera rendering to it

honest osprey
#

Takes in a texture 2d and float for steps which is fed into a posterize node

#

The saving to a PNG was working when the active texture was the rt. So finalrendertexture must not be getting set correctly in the graphics.blit

cosmic rain
# honest osprey The saving to a PNG was working when the active texture was the rt. So finalrend...

I'd also be careful with when you call blit during the frame. The docs mention specific place for urp and hdrp, but I think there was such a constraint in birp as well:

To blit to the screen in the Universal Render Pipeline (URP) or the High Definition Render Pipeline (HDRP), you must call Graphics.Blit or CommandBuffer.Blit inside a method that you call from the RenderPipelineManager.endContextRendering callback.

https://docs.unity3d.com/ScriptReference/Graphics.Blit.html

honest osprey
#

I probably should have mentioned im in the standard rp

cosmic rain
#

Yeah. That's why I mentioned birp. But then again, the docs don't say anything about it. Maybe have a look at the frame debugger and see if the blit command appears there.

cosmic rain
golden garnet
#

I have a question regarding steam achievements. I see that if I am not connected to steam, and a line of code that has something to do with SteamNET runs, it gives me an error. Does this mean I cannot build the game for other platforms like itch.io without having the game error due to it looking for Steam dependencies?

spare dome
#

not sure if this a unity problem

eager yacht
#

You'd basically conditionally compile out anything steam related depending on the platform in use, such as #if !DISABLESTEAMWORKS, as well as the same thing on any steam-related dlls.

queen raft
#

Is there any way to revert a property in all instances of a prefab in all scenes? I don't want to open every scene and manually revert for each prefab instance.

somber nacelle
#

if you mean a serialized field, as long as it hasn't been overridden then simply modifying the prefab should be sufficient

#

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

An overridden property value on a Prefab instance always takes precedence over the value from the Prefab Asset. This means that if you change a property on a Prefab Asset, it doesn’t have any effect on instances where that property is overridden.

shell void
#

Why a normal map preview is red after serialized?

#

Help :>

somber nacelle
#

this is a code channel

shell void
#

i write this normal map into another texture use my code, i get an incorrect result... I am wonder is my code problem or serialize problem

somber nacelle
#

be more specific than "incorrect result"

shell void
#

i notice the preview normal in inspector is in wrong color

#

so have the first question

somber nacelle
#

dragging the object into the slot in the inspector just serializes a reference to it, it does not change the object. most likely your code is wrong somewhere

shell void
#

Yes, that is true. Let me do some code research. Thank you for answer~

lofty summit
#

what is the kosher way to grab the camera nowadays? 🤔
Look for the MainCamera tag? .camera? DIY a solution?

#

(I am using cinemachine, if that helps)

open bluff
#
    public class PlayerCamera : MonoBehaviour {
        private PlayerInput playerInput;

        [Header("Camera Settings")]
        [SerializeField] private float cameraSensitivity;
        private float xRot;

        [Header("Camera References")]
        [SerializeField] internal Transform playerBody;
        [SerializeField] internal Transform cameraRoot;
        [SerializeField] internal Transform headIKTarget, armIKTarget;

        private void Awake() {
            playerInput = GetComponentInParent<PlayerInput>();

            Cursor.lockState = CursorLockMode.Locked;
        }

        private void LateUpdate() {
            Vector2 look = playerInput.lookInput * cameraSensitivity * Time.deltaTime;
            transform.position = cameraRoot.position;

            xRot -= look.y;
            xRot = Mathf.Clamp(xRot, -90f, 90f);

            transform.localRotation = Quaternion.Euler(xRot, 0f, 0f);
            playerBody.Rotate(Vector3.up * look.x);
        }
    }

I am trying to use a camera shake asset in Unity, but the shake does not work because I have synchronised the position of my camera to the camera root object. How can I solve this problem?

leaden ice
#

make a "CameraRig" object with this script on it, and make the camera itself a child of that

open bluff
#

yes, thats work

#

thank u

#

👌

latent latch
#
private IEnumerator RevealCharacters()
{
    while (_currentVisibleCharacterIndex < textInfo.characterCount + 1)
    {
        var lastCharacterIndex = textInfo.characterCount - 1;

        if (_currentVisibleCharacterIndex >= lastCharacterIndex)
        {
            yield break;
        }

        char character = textInfo.characterInfo[_currentVisibleCharacterIndex].character;
        TextBox.maxVisibleCharacters++;

        if (character == '?' || character == '.' || character == ',' || character == '!')
        {
            yield return _punctuationDelay;
        }

        else
        {
            yield return _charDelay;
        }

        _currentVisibleCharacterIndex++;

        if(TextBox.isTextOverflowing)
        {
            yield return _pageEndDelay;
            TextBox.textInfo.pageCount++;
        }
    }
}

So I'm making a typewriter script which works by having the text already presented on the textbox, but revealed in increments. The problem I'm running into is that because it's being revealed and not dynamically appended to, I can't figure out when the text overflows so I can switch the page to the next. There's a few ways I can think of resolving this such as having my own escape character to prompt the page change, but I was wondering if I'm overlooking a method somewhere.

#

TextBox is of type TMP_Text

#

Ah, actually let me try some of these methods out. The problem is these documentations are just a little bare for how much is on them

#

Found a struct of information regarding the current page after digging around a bit more!

pine bronze
#

i have an object that i can pick up by clicking it, and rotate it by scrolling. i want to rotate it up and down, but if i rotate it on the x axis and look from the side it looks like im rotating it left and right. is it possible to make it so if im looking from the side it rotates it on the z axis and if im looking from behind/in front of it it rotates it on the x axis?

pine bronze
ember patio
mild orbit
#

Is there any issue with keeping a static list of GOs/Components? Should still work just fine when switching scenes, right (of course all of the entries would be null though).
No need for a singleton component for the list?

rigid island
#

when you switch scenes all objects are destroyed

mild orbit
#

Right... so it should all be fine then.

rigid island
#

fine for what? I dont understand what your end goal is

mild orbit
#

Object Pooling

rigid island
#

I mean..I would just make it a singleton so i can plug the items in the inspector 🤷‍♂️ then use DDOL to carry it over

#

since statics can never be exposed in the inspector, they belong to the class not specific instance

mild orbit
#

Yeah, I don't need to assign them in the inspector so all good.

rigid island
#

Just remeber statics need to be manually reset

#

esp if you use Domain Reload off like myself

mild orbit
#

Ahh right, I always forget about Domain Reload being togglable, thanks.

prisma hatch
#

hello lads, can anyone help me with finding up to 3 nearest objects toward the center of a trigger?

thick terrace
prisma hatch
#

oh sweet, thanks for the idea!

hexed pecan
honest osprey
#

@cosmic rain

stone pewter
# shell void

long story short I'm pretty sure this is probably because your normal map isn't marked as a normal map in the texture import settings!

#

Unity encodes normal maps in a special way on import, and so any normal map field that should display normal maps, have to reconstruct normals from the encoded format. So, if the original normal map isn't flagged as a normal map texture, it will show up all weird in any inspector designed to draw normal maps specifically, like the one that's showing up in red

#

tldr is that on importing textures marked as a normal map, unity stores the red channel in the alpha channel, and ditches the blue channel entirely

#

(this is for compression/quality reasons!)

#

the blue Z channel is then reconstructed in the shader after unpacking, see UnpackNormal in UnityCG.cginc

golden glade
#

Is it possible to derive from a Rigidbody in any other way or similar?

#

I want to be able to have an individual gravity on a per-object basis by extending Rigidbody, but it doesn't seem to allow me.

public class OrbitalActor : Rigidbody
{
    public Vector3 GravityDirection = Vector3.down;

    public Vector3 BaseVelocity { get; set; }

    public new Vector3 velocity
    {
        get => base.velocity;
        set
        {
            BaseVelocity = value;
            base.velocity = value + GravityDirection;
        }
    }
}

I get this error “the script needs to derive from monobehaviour”

#

How can Rigidbody be added as a component then? Doesn't make any sense.
As Rigidbody does derive from Component

gray mural
golden glade
somber nacelle
#

unfortunately components that you write have to derive from MonoBehaviour, unity does not support creating custom components that do not derive from that for whatever reason

golden glade
#

That's a shame

somber nacelle
#

actually i'm not entirely sure if that restriction is only limited to the editor. you could try adding the component at runtime instead of via the editor's AddComponent menu (though it seems like that may defeat much of the purpose of what you are attempting to do here)

golden glade
#

I wonder why it isn't sealed then lol

#

Rigidbody2D is sealed whereas Rigidbody isn't lol

neat forge
#

The 2d and 3d physics systems are entirely independent (and developed by entirely different people, I believe), so I wouldn't be surprised about discrepancies

golden glade
#

Interesting, maybe something they missed?

gray mural
#

From the reply on this post:

Components and Behaviours are not meant to be used by your own classes. They are used to model the internal hierarchy of built-in C++ components. So those are essentially the C# wrapper classes for the corresponding C++ base classes.

#

That's strange, since I thought you were able to create your own Component

golden glade
somber nacelle
#

anyway, if that doesn't work for you, you could always just write a regular MonoBehaviour component that just adds force to the object every fixed update in your desired gravity direction and turn off the Use Gravity option on the rigidbody.

[RequireComponent(typeof(Rigidbody))]
public class CustomGravity : MonoBehaviour
{
  public Vector3 GravityDirection;
  [SerializeField] private Rigidbody _rb;
  private void FixedUpdate() => _rb.AddForce(GravityDirection * Physics.gravity, ForceMode.Acceleration);

  private void Reset()
  {
    GravityDirection = Vector3.Down;
    _rb = GetComponent<Rigidbody>();
  }
}
honest osprey
merry stream
#

how can i properly serialize a tree with newtonsoft? I believe there's some issues when serializing "Parent" since only the first node has a parent in the json file which makes sense since it would technically be infinitely "serliaziling." is there a workaround? https://gdl.space/pidejapiqa.php

rapid radish
#

My Intellisense in VS Community keeps breaking randomly? It usually works, but sometimes doesn't, per the snapshot - but it still has the 'references' text. Already tried clearing out .sln and .csproj files, and hitting regenerate project files - those seem to fix it, but then the problem appears again.

Unity 2022.3.45f1, Visual Studio Community 2022.

Any help appreciated!

somber nacelle
somber nacelle
#

well then i have no idea what might be causing that issue. what you've described is usually caused by what I asked about which is fixed by launching unity as administrator and assigning that setting then relaunching
visual studio tends to JustWork™️ and provided you actually open it by double clicking a script in your project within the unity editor it should be able to load the solution and projects just fine

golden garnet
#

Trying to activate a gameObject while timeScale = 0. Is this possible?

spare dome
#

When timeScale is set to zero your application acts as if paused if all your functions are frame rate independent. Negative values are ignored.

golden garnet
somber nacelle
#

show what you tried because SetActive has literally nothing at all to do with the time scale

golden garnet
#

Which is odd considering I thought that Update is frame-rate independent

somber nacelle
#

well no, update specifically runs every frame. but unless you are doing anything that uses the time scale (like deltaTime), then the time scale is irrelevant

golden garnet
#
    {
        pauseMenu.SetActive(true);
        Time.timeScale = 0f;
        postProcessingScript.currentdepthIntensity = 0f;
        GameManager.isPaused = true;
        Cursor.lockState = CursorLockMode.None;
        if (GameManager.usingController)
        {
            EventSystem.current.SetSelectedGameObject(pauseMenuBackButton.gameObject);
            conNav.SetActive(true);
        }
    }```
My pause function. Trying to have the "conNav" activate if the player is using a controller. For some reason, conNav never activates under these conditions.
spare dome
#

thats why its on the physics update

somber nacelle
golden garnet
#

confirmin rn

mossy snow
#

and does conNav have any Animator on it that, say, fades in the menu?

golden garnet
merry stream
#

can anyone help me with this serialization/deserialization issue? the tree appears to be serialized correctly but when loading back in it seems like the NodeData of each node is being lost, specifically the GUID and unlocked state. https://gdl.space/yomacurede.cs, any ideas? everything else is intact and loads correctly it appears.

rapid radish
somber nacelle
#

that would fix the issue i thought it might be, but is unlikely to do anything for the issue you are actually experiencing

hot ledge
#

Posting this question in this chat as well, since idk which one is best for this

I want to constrain a dynamic rigidbody to only move along a spline which I've sort of figured out how to do in two ways.

void FixedUpdate()
{
  SplineUtility.GetNearestPoint(rail, rb.position, out var nearest, out float _);
  transform.position = nearest;
  rb.velocity *= Vector3.Dot(rb.velocity, transform.forward);
}```In this first method, I'm able to keep the rigidbody locked to only move along the spline, but collisions bug out frequently, at least when messing with things in scene view. 

```cs
void FixedUpdate()
{
  SplineUtility.GetNearestPoint(rail, rb.position, out var nearest, out float _);
  
  rb.AddForce((new Vector3(nearest.x, nearest.y, nearest.z) - rb.position)*10);
}```In this second method, the physics are more stable, but the rigidbody isn't locked to the spline, it just gets pushed towards the nearest point on it.

Is there any better approach to doing this or am I missing something?
cosmic rain
ocean vector
#

Hi, I’m trying to make a game about trains where I build the tracks as the train moves forward. I wanted my tracks/rails to be prefabs with a portion of the track. I'm trying to use splines for this, but since they are different prefabs, their spline containers are different, and I'm unable to make the connection. Has anyone who has worked with splines figured out if these connections can be made?

cosmic rain
cosmic rain
cosmic rain
hot ledge
cosmic rain
#

If so, then obviously it would try to remain on the spline. The one causing the clipping is probably your cube, that is not moved by physics.

hot ledge
cosmic rain
merry stream
cosmic rain
merry stream
#

when it gets deserialized

#

i assumed it was an issue with the PassiveNode class holding a reference to the parent but that is not being serialized since it would create an infinite loop

#

so I just reassign the parents by traversing the tree

cosmic rain
merry stream
#

if you look at the gdl space its at the top

#

thats an example of a saved item

cosmic rain
#

So the guids are serialized correctly

#

If they can be serialized, they can probably be deserialized as well. I'd try logging things every step through the deserialization process. Or even better, step through the code with a debugger.

merry stream
cosmic rain
merry stream
#

its pretty clunky i assume i could do it better

#

but it works for now

#
{
    public string GUID;
    public PassiveNode treeRoot;
    public GenericDictionary<string, Vector2Int> nodePositions;
    public string randomName;
    public RarityType rarity;
    public int quantity;
    public GenericDictionary<ItemStat, float> affixes;
    public GenericDictionary<ItemStat, float> implicits;
    public int itemLevel;
    public int sellPrice;
}```
cosmic rain
# merry stream ```public struct ItemSaveData { public string GUID; public PassiveNode t...

Did you try logging the guid value that it has on load?

public override void JsonLoad(SaveSystem system)
{
    //pair of item instance and index
    List<KeyValuePair<ItemSaveData, int>> data = system.LoadData<List<KeyValuePair<ItemSaveData, int>>>(savePath);
    if (data == null) { Debug.LogError("Failed to load inventory"); return; }

    for (int i = 0; i < data.Count; i++)
    {
        Debug.Log($"data {i} guid: {data[i].Key.GUID}");
        ItemInstance item = ItemDatabase.RebuildItem(data[i].Key);
        AddAtIndex(new ItemStack(item, data[i].Key.quantity), data[i].Value);
    }
    OnItemsUpdated.Raise(null);
}
merry stream
#

yeah its just an empty string ""

#

and the bool unlocked is set to false

cosmic rain
#

Assuming you actually logged it and not making an assumption, the issue is probably in the deserialization.
Can't really help with that as I'm not sure what requirements Newtonsoft has for correct deserialization.

merry stream
#

hm i fixed it by changing the property name from guid to nodeGUID, maybe there was some naming conflicts since the itemInstance also has a field named guid? no idea but weird issue

merry stream
# cosmic rain Possible

ah i actually figured out the real reason. In my class i have private fields and then public getters as such "public string NodeGUID => nodeGUID. These functions were being serialized and not the private field so when it was deserialized it wasn't able to change the value of the private field. For some reason this doesn't occur with reference types and I never encountered this before since I was always serializing SO's which had [SerializeField] attribute on the private fields. I have to mark the private value fields with [JsonProperty] for them to properly serialize/deserialize

cosmic rain
merry stream
#

guess so, any idea why it works fine with reference types?

somber nacelle
#

i just went back and looked at your code, and what value types is it not working with? because the issue you seem to have is only related to reference types 🤔

merry stream
#

i assume it might be because you can't just overwrite the value type directly as you can with reference types?

merry stream
#

newtonsoft only serializes the public getters unless the private field is marked with JsonProperty

somber nacelle
#

right and string is a reference type. the issue is not related to reference vs value types, it's specifically because that NodeData class has read only properties that you serialized, but had no way to deserialize them because the properties themselves were get-only (meaning they cannot be assigned to) and unlike the PassiveNode class you don't have a JsonConstructor specified that would be able to assign to the backing field

merry stream
#

hm you're right

#

i forgot that string are referene types

#

well I got rid of the nodeData class and just have this in my PassiveNode class and the issue persisted, just trying to wrap my head around where I went wrong ```public class PassiveNode
{
[JsonIgnore] private PassiveNode parent = null;
private GenericDictionary<ItemStat, float> nodeStats;
private List<PassiveNode> children = new List<PassiveNode>();
[JsonProperty] private string nodeGUID;
[JsonProperty] private bool isUnlocked;

public PassiveNode Parent => parent;
public List<PassiveNode> Children => children;
public GenericDictionary<ItemStat, float> NodeStats => nodeStats;
[JsonIgnore] public string NodeGUID => nodeGUID;
[JsonIgnore] public bool IsUnlocked => isUnlocked;```
#

this works fine though

somber nacelle
#

why bother with explicit backing fields here instead of auto properties with a private setter?

merry stream
#

yeah that works too

#

of course

#

its just the way ive written all my classes though

#

i prefer this to auto properties

#

is it the same thing that would cause it here as well?

#

as you stated above

cosmic rain
#

Just reading the serializer docs a bit, it seems to be serializing properties, and not fields. Might be wrong though. The docs are not making this clear from the very start.

merry stream
#

yeah it does since in the json file it shows "Children" and not "children"

#

same for all of them

somber nacelle
merry stream
#

never noticed since i only change the capitalization

somber nacelle
#

so instead of

[JsonIgnore] public bool Thing => thing;
[JsonProperty] private bool thing;

it would just be [JsonProperty] public bool Thing { get; private set; }

merry stream
#

yep got it

somber nacelle
#

and it does exactly the same thing as what you have, but shorter

cosmic rain
merry stream
#

but how come i dont have the same issue with the other variables

#

children, nodestats, etc

somber nacelle
#

because you have the JsonConstructor

merry stream
#

ah makes sense

#

wait this? ``` [JsonConstructor]
public PassiveNode(List<PassiveNode> children, GenericDictionary<ItemStat, float> nodeStats, string guid, bool unlocked)
{
//Debug.Log($"Creating node with {children.Count} children, {nodeStats.ElementAt(0).Key} {nodeStats.ElementAt(0).Value} stats and {nodeData.NodeGUID} guid");

    this.children = children;
    this.nodeStats = nodeStats;
    this.nodeGUID = guid;
    this.isUnlocked = unlocked;
}```
somber nacelle
#

yes

merry stream
#

it also sets the guid and unlocked tho?

somber nacelle
#

well yes, now it does. before it didn't so you had the issue

#

and also those weren't even part of this class in the previous code that had the issue

merry stream
#

yeah ive been messing with things

#

but if i remove the [JsonProperty] attribute it breaks again

#

meaning the constructor is not what fixes it? or am i missing something

somber nacelle
#

ah yes, because the ctor parameter's names are different than the property names

#

the only thing that can be different is capitalization afaik

merry stream
#

ohh

#

so it should be string nodeGuid and isUnlocked for the serializer to properly match it?

#

in the params

somber nacelle
#

yes

merry stream
#

makes sense

somber nacelle
cosmic rain
merry stream
#

makes a lot of sense, didnt know about the matching params thing

#

appreciate it

#

also makes sense why when I tried to use [JsonIgnore] on the parent variable it wasnt working

#

has to be used on the getter

craggy pivot
#

Does anyone know the behavior for when a 2d raycast passes perfectly through:
a) A corner of a collider, but not into the bounds of the collider
b) Parallel and on the same plane as an edge (eg, an edge defined with points (1,2) and (2,2) and a raycast from (0,2) directly to the right)

Does this just depend on floating point precision? Like a liiiittle to the left or right will just be 50/50 on whether it hits or not?

cosmic rain
#

Yes. It's gonna be up to a floating point error and possible would provide different results in different situations.

craggy pivot
cosmic rain
#

Well, there's gonna be a precision limit no matter what you do, so it's fine if there's a small error in the detected wall position.

craggy pivot
#

I see, so maybe I should just add like 0.001 radians to my angle and raycast for the next wall?

cosmic rain
#

What part of the article are you talking about exactly? Are you just casting a ray every few angles or what?

lean sail
craggy pivot
#

Trying to make a visibility polygon like in the article, and I have the points numbered in radial order but I don't know how to proceed in raycasting from edge end points to the next closest wall.

craggy pivot
cosmic rain
craggy pivot
#

omfg

#

thats so obvious

#

Thank you

upper pilot
#

How do I create a function that will accept a generic struct and search for specific type in that struct?
I want to loop trough a List<struct> and find Image or other component and delete a game object assiociated with it.

#

The reason I want it generic is so it's not dependent on custom class/struct(it's for my Helpers functions that can be reused)

#

As an example(which perhaps can be improved?)


    public static void DestroyAllChildren(Dictionary<string, Image> dict)
    {
        foreach (Image child in dict.Values) Object.Destroy(child.gameObject);
    }
    public static void DestroyAllChildren(Dictionary<string, SkeletonGraphic> dict)
    {
        foreach (SkeletonGraphic child in dict.Values) Object.Destroy(child.gameObject);
    }
#

I need something similar but for a custom struct which will contain either Image or SkeletonGraphic in my case, but the helper method won't be aware of what struct I have passed.

#

I need a struct to allow duplicate "keys" so I can't use dictionary anymore.

#

(It can also be a class instead of a struct if that makes it easier)

cold parrot
#

those structs need to implement a shared interface or base type for that purpose that exposes the fields/properties/methods you want to call. Alternatively you can test if an ‘object’ is of a certain type. A generic type argument doesn’t really help you there without the objects having something in common to operate on.

knotty sun
upper pilot
#

I want to avoid having shared type, unless its a built in one, since inn another project that struct wont exist anymore and my Helper class would throw an error

cold parrot
upper pilot
#

so I have to loop through struct in my code directly and delete objects from there?

#

Is there a different way to set it up to allow for my helper class to handle it?

#

I guess that I can create a List out of the struct then pass it to my Helpers class

#

All it needs to do is destroy gameobjects

#

I could also probably just swap the order Dict<Image, string> but that feels wrong.

cold parrot
#

that makes no sense

upper pilot
#

the issue is that <string> is duplicated

cold parrot
#

What do you actually want to implement that needs this kind of thing?

knotty sun
upper pilot
#

I am saving tags with an image, so they can be cleared from the list, tags are saved to json so I can recreate the scene on game load.

#

Tags have all information to recreate the image.

#

if we try to draw same image twice without removing it first from the Dictionary, it throws an error for a duplicate key.

#

I can fix my issue with this:

foreach(ImageTags image in DisplayedImages)
{
    Destroy(image.image);
}
foreach (SpineTags spine in DisplayedSpineFiles)
{
    Destroy(spine.skeletonGraphic);
}
#

I was just looking for a cleaner way

knotty sun
upper pilot
#

So I can do what I did before:


        Helpers.DestroyAllChildren(DisplayedImages);
        Helpers.DestroyAllChildren(DisplayedSpineFiles);
upper pilot
#

the one case I can imagine is if we add random property to the tag which would make sense to have more than 1 of these.

#

otherwise if the tag is the same with specific values then it doesn't seem to make sense to have duplicate, I agree.

#

Its for an Inky game

#

we parse tags from the json file that gives them to us as the story progresses.
I need to save them so I can recreate the scene with correct images on the screen, music playing etc.

#

by random I meant like

#particle:asset'bubble',random'true',minSize'5',maxSize'15'

You could add those particles multiple times in a row and it would make sense(they would cover more and more of the screen, but also be random)

#

Thats kinda the edge case, but I am sure there might be more to come

knotty sun
upper pilot
#

How does that work? string cant be duplicated right?

knotty sun
#

no,, you add the duplicate to the List

upper pilot
#

oh

#

that almost works, but they need te be in order they were added

#

so when scene is recreated they are at correct z depth.
Even tho we have z depth already, but if we have 2 images on same z depth they will appear based on the order they were created.

#

But thats close 😄

#

Maybe a List of Tuples?

#

List<Tuple<string Image>>

#

not sure the syntax, but that might be what I need

cosmic rain
upper pilot
#

what are containers?

cosmic rain
#

It kinda sounds like what you need is sort of a parser

upper pilot
#

Like a tuple basically?

cosmic rain
upper pilot
#

yes thats what I do now

cosmic rain
#

Like your string and a list of whatever

upper pilot
#

but then the struct is not generic enough to put a script in my Helpers class

#

Which was my main reason for this question

cosmic rain
#

Make it generic

upper pilot
#
//NEW
  foreach(ImageTags image in DisplayedImages)
  {
      Destroy(image.image);
  }
  foreach (SpineTags spine in DisplayedSpineFiles)
  {
      Destroy(spine.skeletonGraphic);
  }

//OLD
  Helpers.DestroyAllChildren(DisplayedImages);    
  Helpers.DestroyAllChildren(DisplayedSpineFiles);
cosmic rain
#

That code doesn't tell me anything without knowing the context

upper pilot
#

I was told it's not possible the way I do it, is there another way? A way that doesn't make a Helper class be dependant on a custom class/struct?

cosmic rain
upper pilot
#

ah yeah sorry, the Old version used a Dictionary<string, Image>

cosmic rain
#

Where did it use it?

upper pilot
#

Ok, let me write it down

lean sail
#

werent you told its possible just using an interface or base class? i skimmed over the convo a bit but its really unclear whats actually stopping you from making this work

upper pilot
#

Those are from my helper class, that I can reuse in multiple projects which have different scripts etc.(so same custom class/struct won't appear in other projects)

    public static void DestroyAllChildren(Dictionary<string, Image> dict)
    {
        foreach (Image child in dict.Values) Object.Destroy(child.gameObject);
    }
    public static void DestroyAllChildren(Dictionary<string, SkeletonGraphic> dict)
    {
        foreach (SkeletonGraphic child in dict.Values) Object.Destroy(child.gameObject);
    }
cosmic rain
upper pilot
#

I think its quite simple, there are just 2 versions to show so there will be few lines of code, but I will try to keep it simple

#

My custom class that runs game logic etc:


    Dictionary<string, Image> DisplayedImages = new();
    Dictionary<string, SkeletonGraphic> DisplayedSpineFiles = new();

    public void RemoveImages()
    {
        Helpers.DestroyAllChildren(DisplayedImages);    
        Helpers.DestroyAllChildren(DisplayedSpineFiles);
        DisplayedImages.Clear();
        DisplayedSpineFiles.Clear();
    }
#

That's the old way

#

But <string> cant be duplicate, so now I need a way that allows for duplicate string, but also let me use my Helper class methods(I can make a new method if it works without having a custom class dependency in the Helpers class)

upper pilot
#

So someone did mention to use UnityEngine.Object I believe as a base class.

#

you can't add same key to the dictionary twice.

#

but I have a case where it might happen

cosmic rain
#

Indeed. maybe a string is not an appropriate key then.

upper pilot
#

Which is why I am trying to fix it.
So my curent fix is to use a List<struct> which is fine, but I can't use Helper script anymore as it would be dependant on my custom struct.

cosmic rain
#

How are you discerning between different keys if they are the same string?

upper pilot
#

I don't, just got this issue so I am looking for a way to fix it.
The fix is simple if I ignore my helper class, I just wanted to know if there is a way to keep it 😄

cosmic rain
upper pilot
#

What do you mean?

#

oh yeah

#

I am not sure how to do that

cosmic rain
#

Helper.GenericMethod<Type>(param);

upper pilot
#
public struct ImageTags
{
    public string tag;
    public Image image;
}
public struct SpineTags
{
    public string tag;
    public SkeletonGraphic skeletonGraphic;
}

List<ImageTags> DisplayedImages = new();
List<SpineTags> DisplayedSpineFiles = new();
#

Yeah but doesn't that mean I have to give it a correct type?

#

or is "Type" a generic type?

#

I know there is T, but I used it very rarely so I can't remember now

upper pilot
#

So that means my Helper class will be dependant on having that type in the project right?

lean sail
#

T is just the name you can give a generic type

upper pilot
#

So that's what I want to avoid.

upper pilot
#

Because I want to use my helper class in other projects.

#

and I don't want to bring those structs/classes with it.

cosmic rain
#

Well, it's kinda silly. You're trying to avoid something fundamental to how C# works

lean sail
#

this helper functionality honestly looks so specific to your use case, i dont see why you would even worry about using this in other projects

cosmic rain
#

It's like, you want to eat, but you refuse to open your mouth

knotty sun
#

if both of your target objects are Monobehaviours why not use that instead of Image or SkeletonGraphics

upper pilot
#

What do you mean? I just want to reuse a helper script that handles Unity related work.

upper pilot
cosmic rain
upper pilot
#

Maybe its silly, idk we will see in the future 😄

upper pilot
upper pilot
#

as long as I keep Image/SkeletonGraphic on separate list

cosmic rain
#

If you use generic constraints(which you'll probably need to do if you want access to specific fields), then they would only depend on that constraint. You can't avoid that.

upper pilot
#

So in my head I was thinking of having a way to loop through a List of "struct"(generic) and search its properties for specific type(Image, SkeletonGraphic)

#

But maybe that's not a thing, or a bad practice

lean sail
# upper pilot I am already using it, trying to slowly build on it

i mean the original helper function you had used a dictionary, and then proceeded to ignore the actual part of it being a dictionary because you wanted to just destroy a list of gameobjects.
the same thing applies here to your structs, this seems so very specific to a structure in your code that i dont see a reason to actually need this as a helper function. It sounds like you just want to destroy a list of objects

upper pilot
cosmic rain
lean sail
#

this isnt really a helper function anymore, just a way for you to save 3 lines and have really questionable code elsewhere

lean sail
upper pilot
upper pilot
cosmic rain
upper pilot
#

What do you mean by "you had used a dictionary, and then proceeded to ignore the actual part of it being a dictionary"?

#

I need to keep <string> connected to <Image> on my side

#

But yeah, I can just recreate a List<gameobject> and destroy them too.

lean sail
upper pilot
#

The point of that is that my project might have a different structure, like Dictionary<string, Image> or now List<struct>
Because of my needs, but the helper function doesn't need to know that, if I pass a Dictionary to it, it just needs to loop through it and remove gameobjects.

#

Is it wrong approach?

cosmic rain
upper pilot
#

Maybe that's fine idk, I just liked the way of typing Helpers.DestroyAllChildren() and pass different data type for it to handle it.

#
    public static void DestroyAllChildren(Transform t)
    {
        foreach (Transform child in t) Object.Destroy(child.gameObject);
    }
    public static void DestroyAllChildren(List<GameObject> objects)
    {
        foreach (GameObject child in objects) Object.Destroy(child.gameObject);
    }
#

Is it that bad? 😄

cosmic rain
cosmic rain
upper pilot
#

I am fine for it to be generic, if it uses built in types

#

not custom

cosmic rain
upper pilot
#

Because built in types are shared in other projects, so thats 100% good for me

#

GameObject is part of Unity right?

#

So that's a built in type for me

cosmic rain
#

Then create a type that would be shared in all the projects

upper pilot
#

C#/Unity, just not custom struct/class that I created.

upper pilot
cosmic rain
#

If you're creating a framework for several projects, obviously you want your own types that would be considered "built-in"

upper pilot
#

Since I am already using a Helper class, I might as well have a Helper List of things I tend to use often

upper pilot
lean sail
# upper pilot Is it wrong approach?

yes, and thats what im saying about your helper functions. yes it takes in a dictionary, but only because your structure wants it to. What if one day you have a new structure of gameobjects? suddenly your helper function would need to be added to. Again this is very very specific to your structure and seems like you're just are trying to save lines

upper pilot
#

My approach was: If I do something often, I should write a helper script for it.

cosmic rain
#

And you can make it abstract enough by just sharing interfaces.

cosmic rain
upper pilot
#

When I am tired and I can't remember how to check if index is within a range:

    public static bool NumberWithinRange(float number, float minRange, float maxRange, bool inclusive = true)
    {
        if (inclusive)
        {
            if (number >= minRange || number <= maxRange) return true;
        }
        else
        {
            if (number > minRange || number < maxRange) return true;
        }
        return false;
    }
upper pilot
#

if i dont delete them, then I disable them. I still have repeated code.

cosmic rain
lean sail
#

im not sure how many different places you're destroying children objects from, but id really only have helper functions in places that you're either doing complicated stuff or they're at least a few lines long

#

even that NumberWithinRange function, id consider how often you're really using it.

upper pilot
cosmic rain
#

Or rather a "UIList" or something class.

upper pilot
upper pilot
weak iron
#

`using UnityEngine;

public class PlayerShooting : MonoBehaviour
{
public GameObject bulletPrefab; // The bullet prefab to instantiate
public Transform firePoint; // The point where bullets are fired from
public float fireRate = 0.5f; // Fire rate in seconds
private float nextFireTime = 0f;

void Update()
{
    // Get the mouse position in world space
    Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    mousePos.z = 0; // Ignore Z axis for 2D

    // Calculate the direction between the gun and the mouse position
    Vector2 direction = (mousePos - firePoint.position).normalized;

    // Rotate the gun towards the mouse
    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    firePoint.rotation = Quaternion.Euler(new Vector3(0, 0, angle));

    // Shoot when the left mouse button is pressed and cooldown allows
    if (Input.GetMouseButton(0) && Time.time >= nextFireTime)
    {
        Shoot(direction);
        nextFireTime = Time.time + fireRate;
    }
}

void Shoot(Vector2 direction)
{
    // Instantiate the bullet at the fire point
    GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
    BulletMovement bulletMovement = bullet.GetComponent<BulletMovement>();
    
    // Set the bullet's direction
    bulletMovement.SetDirection(direction);
}

}`

i told chat gpt to make me an bullet script but everytime i press click it dosent shoot pls anyone

#

and this is my bullet script
`using UnityEngine;

public class BulletMovement : MonoBehaviour
{
public float speed = 10f;
private Vector2 moveDirection;

public void SetDirection(Vector2 direction)
{
    moveDirection = direction.normalized;
}

void Update()
{
    transform.Translate(moveDirection * speed * Time.deltaTime);
}

// Destroy the bullet after a certain time or when it goes off-screen
private void OnBecameInvisible()
{
    Destroy(gameObject);
}

}
`

fallen meteor
#

im making a 3D shooter game rn, working on interactions. I have my Interact() marked as override but it still gives me this error:
Assets\Scripts\Interactables\Keypad.cs(18,29): error CS0506: 'Keypad.Interact()': cannot override inherited member 'Interactable.Interact()' because it is not marked virtual, abstract, or override
any help?

weak iron
weak iron
#

Base Class (Interactable)
public class Interactable : MonoBehaviour { public virtual void Interact() { } }
Derived Class (Keypad)
`public class Keypad : Interactable
{
public override void Interact()
{
}
}

`

fallen meteor
#

Derived class

weak iron
#

ye

#

ye

fallen meteor
weak iron
#

wait lemme give u another script

#

Base Class (Interactable)
using UnityEngine;

public class Interactable : MonoBehaviour
{
protected virtual void Interact()
{
}
}

#

Derived Class (Keypad)
using UnityEngine;

public class Keypad : Interactable
{
protected override void Interact()
{
}
}

lean sail
weak iron
#

ight

fallen meteor
# lean sail show the Interactable class
using System.Collections.Generic;
using UnityEngine;

public class Keypad : Interactable
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    protected override void Interact()
    {
        Debug.Log("Interacted with " + gameObject.name);
    }
}```
weak iron
lean sail
weak iron
#

or give me a video

#

il script after it

#

if u can

lean sail
soft shard
weak iron
#

so the first time i coded by a yt tutorial nothing worked and told him to help me and now it dosent shoot and when i enter game my bullet prefab just dissapears or turns in a object and the game is 2d btw

soft shard
#

Alright, that sounds like a good description of the problem, but do you actually understand the code that you are using?

weak iron
#

not really cause i just started the script but i understand some things of it cause i watched some tutorials and can understand a little

soft shard
#

The problem with AI generated code is that it doesnt really understand C# or Unity, its pulling a bunch of text from online resources to generate a response that sounds like what you want to hear, and without understanding the code it gives, it would be difficult to provide help - maybe you could try adding some breakpoints or Debug logs to figure out what the code is doing, or what I usually do is take a step back and break down the goal into small steps, then try to figure out how to build and test each step till you get something functional - AI code is great for ideas but will rarely work "out of the box" from what ive seen

weak iron
#

👍 thanks bro il go check some tutorials
have a good day/night

soft shard
#

Well my suggestion was more debugging and breaking down the problem further, but if you want to try more tutorials you can give that a shot too

weak iron
#

yeah il try the debug and after tutos

#

anyway thanks

spark flower
#

hey guys, how can i search for a specific class that is a child of another class? basically i have Health, Stamina and Mana classes and a parent class Status. so for example i want to find if i have Health component , how do i specify that in the function?

soft shard
spark flower
#

the problem is the parameter

#

i want to specify there so i can remove this switch from the function

soft shard
# spark flower i want to specify there so i can remove this switch from the function

Maybe its not clear the purpose of this function, even if you changed your int param to a Status param, youd probably still be checking the type with something like if(status.GetType().Equals(typeof(Health)) { ... } else if(...) { ... } which, if you plan to add more than those 3 types, this approach can over time become difficult to manage

spark flower
#

if the status is not existant in the folder then it wuld just return null

edgy bough
#

How can I render a camera's view on top of another camera? I'm trying to have some objects rendered separately, but I can't get the camera for those objects to actually show something. I'm using the built-in Render Pipeline

#

I got it to render to a RenderTexture properly but I have no idea how could I show it on-screen

soft shard
spark flower
#

how wuld i ask if it has a specific type?

soft shard
# edgy bough I got it to render to a RenderTexture properly but I have no idea how could I sh...

RenderTextures can be used to show what a camera sees on UI, and a RawImage component can accept render textures as the "sprite" - unless your goal is to layer cameras in the game world and not on UI so for example camera A shows object A but not object B, and vice versa for camera B (some FPS games do this to render the weapon on a different camera than the character to avoid clipping through the game world, that is a bit different than showing what a different camera sees on UI though)

soft shard
# spark flower how wuld i ask if it has a specific type?

status folder could either keep track of its children type and you can use a list or something similar to compare, or you could use your GetComponent call and check if its type is the same as your params type, or if your GetComponent returns null using the param type for the GetComponent call, there is also GetComponent(Type t) instead of GetComponent<T>() which does the same thing but lets you pass a object/param instead of a direct type

spark flower
#

yes but how can i specify in parameters what type am i looking for?

soft shard
#

The same way you originally had, they all derive from the same base type so your param could be Status someParamName then you check against/with someParamName for the underlying type

orchid pivot