#archived-code-general

1 messages Ā· Page 425 of 1

rocky heron
#

xD

somber nacelle
#

and fwiw, i just installed that version of the editor and created a project in it and i can see the newer versions of the packages mentioned

somber nacelle
#

that is something you should absolutely learn about and use. version control software (like git or unity version control) can save your ass

#

you should always be using version control with your projects, especially if it is something you intend to work on for a while

rocky heron
#

alr ill redownload that then

rocky heron
#

with that do you mean unity 6 or 2022.3.58f1?

swift falcon
somber nacelle
swift falcon
pastel halo
#

Hey, how do top down games usually do damage with melee types?
I've been trying multiple methods and each has a drawback. I'm looking to create Vrising style snappyness.

  1. Tried collider based, but apparently that's expensive especially if I want enemies to share the same system and especially if there are alot of them.
  2. Currently trying physicals overlap. requires a special setup, but apparently checking frame by frame is cheaper than using physics. The issue is that its dependent upon the animation as well.
  3. Considering decoupling animations from logic. Spawning a fake/invisible weapon that rotates flush to "sort of" match the weapon. Desync may occur, but it will always hit the target
  4. Considering a slash mesh with either a meshcollider, or multiple rotated/stacked physics overlaps fanned out to get a crescent shape.

issues with animation based colliders- timing is based on animation swing, and the accuracy of the angle. since im going for top down, i've already seen an issue where from the top a slash appears horizontal, but in fact is angled and it totally misses some colliders. thats a serious issue.

I frame by framed Vrisings attack anim, and it looks like damage is dealt BEFORE the animation completes, so it can't be a collider based (on the weapon) and the slash vfx also appears. So it infers that it's a physics overlap or mesh that pops in after a short delay to deal damage.

Like click -> short delay -> damage; while anim starts on click and just finishes when it can.

I plan on making the anims fast and snappy, so the desync shouldn't matter as much. Kinda like Vrising/Hades level of intensity.

Are there any other styles of AoE/crescent type slash detection methods? collider/weapon based seems to be problematic. Though physics overlap has its own drawbacks like manual calls (which apparently is cheaper, since no physics is involved). Any ideas on the best to achieve snappy and semi-accurate feedback? Raycast was also a suggestion*

leaden ice
swift falcon
#

Lots of enemies you say? Use DOTS hehehe

pastel halo
leaden ice
#

i.e. Physics2D.OverlapXXX or Physics2D.XXXCast

#

direct queries simplify things by a lot. You don't need to worry about tunneling. You don't need to worry about waiting for a physics update before getting a callback. You do the query and immediately get a result

pastel halo
#

physics 2d in a 3d space would work? some of the trigger volumes are shorter/taller so weapons may not reach it

leaden ice
#

no

#

sorry

#

thought you were talking about a 2D game

#

Use the 3D queries

pastel halo
#

o gotcha, that makes sense for 2d*

leaden ice
#

same answer just with Physics.XXX

pastel halo
#

sec, trying to read your suggestion again

#

is it almost like a raycast- but a volume, so in the frame of, it immediately returns if something was hit or not?

leaden ice
#

What are we talking about here?

#

There are many different physics queries

#

some of them use volumes

pastel halo
#

Ok, i'm trying to get a crescent slash AoE, im assuming that doing a broad stroke volume that just immediately hits everything in a few frames is the way to go, thats the kind of query i want

leaden ice
#

You can just use OverlapSphere

#

and then filter out anything that isn't in the correct range of angles

pastel halo
#

hmm interesting, that would be CONSIDERABLY easier

#

almost like an explosion check, physics overlap works great for single frames on something like that

leaden ice
#

you could also simplify it to a Box

#

the particle effect doesn't have to perfectly match

#

usually it's good enough to be close

pastel halo
#

hmmmm, cheap but effective. I could attach the box to a transform and rotate + check every frame like i do now?

leaden ice
#

or you could do a an array of like 5 overlapspheres in a crescent shape

#

there are many possibilities

leaden ice
pastel halo
#

my current physics overlap box stuff (attached to actual weapon w/ anim) works. that should def work

leaden ice
#

no GameObjects or components required

pastel halo
#

o gotcha

leaden ice
#

you just do the math, and call the Physics.OverlapXXX thing

pastel halo
#

ya im beginning to see now, that's way easier in terms of setup

#

like the anim/vfx can be totally decoupled and damage is gauranteed

#

whereas right now, its too reliant on those and its a problem

#

thanks, that really helps clear things up

#

on a side note- is there a way to force unity to render animations/scripts simulatenously to prevent desync?

#

i think i could gate things with a coroutine, and some desync might still occur

leaden ice
#

that ensures the physics check will happen at the exact moment in the animation you want

pastel halo
#

ahhhhhhh ok, so the event calls when to begin. rather than a class initializing it. incase the anim is delayed somehow

#

i was just wondering if its possible to force unity to always do something. iirc time vs time.delta and all that and individuals PC frame rate can hamper things

leaden ice
#

None of that is a concern with an animation event

#

it will happen

pastel halo
#

if there was any syntax to make it gaurantee logic is executed verbatum at a specific time. i will def use anim events

#

ya, just wanted to see if i could avoid using anims events, since the events get dropped sometimes when i update anims

swift falcon
pastel halo
#

the idea was to keep everything in a class to totally decouple it from unity systems, much easier to edit to

#

i have alot of animations. but i'll stick with anim events for now

wraith cobalt
swift falcon
rocky heron
#

my packages now dont have a green but a white checkmark, but i only have a remove button for them, not update. and some unlock buttons

somber nacelle
#

yeah that's weird, sounds like there's something fundamentally wrong with your project if you're still not seeing newer versions of those packages available

rocky heron
somber nacelle
#

collections and unity transport both definitely have newer versions and those are also the ones that were related to your earlier issue

steady bobcat
#

sometimes you need to update your editor patch version to get later versions OR it just refuses to let you go up a major package ver without changing it yourself

#

e.g. a proj i work on was on cinemachine v2 but to go to v3 i had to change the version myself in packages.json

heady iris
#

you can peek in the Version History section for the package

rocky heron
heady iris
#

It probably only shows that to update to the newest patch release

ember sable
somber nacelle
solar jungle
#

hey there! could somebody give me some help on how youd put together an weapon-altering item system, best example think binding of isaac. basic things like stat changes/character alterations/custom effects

#

like i know what it all needs to do but the moment i try and code it, it turns into a mess and its easier to start over and try a different approach than to try and fix it notlikethis

broken mantle
#

could you explain more

solar jungle
#

ill clarify, i dont mean in the sense of what types of objects and classes do i need to create to make items. ive got an intermediate knowledge and plenty of experience so i know the fundmental things like that

latent latch
#

composition

solar jungle
#

i find that sometimes ill extend something too much, try to correct by going the other way and it becomes very stiff

latent latch
#

isaac actually has a bunch of edge cases

#

and is very much spaghetti

broken mantle
#

we all have spaghetti code what's new

night harness
latent latch
#

the system was actually fine very early on, but as the dev wanted to add more stuff it wasn't maintainable

solar jungle
#

well right now i dont have anything besides piles of piles of scripts that are obsolete, I upgraded to 6.0 so a clean slate is nice

latent latch
#

If you do want this nice modular system, the best you're going to get is chopping up the behaviours as much as possible

#

then your choice of a super class or by making unique objects for each one of these weapons and having a custom sequence of logic for each (how all these behaviours are glued together)

night harness
#

Some sort of way to compose an order of execution sounds very nice for something like this

latent latch
#

I do think having a object type per weapon is the ideal solution, so this way you can deal with edge cases more discreetly

#

Isaac, besides the default weapon, has a few different weapon modes which affects a lot of the weapon modifiers

#

which is why you do need some more handling with how each of those modifiers are applied

night harness
#

Could be worth actually making a little issac mod to get a rough vibe of how that pre-existing workflow is functioning

latent latch
#

There is a priority system for each of the weapons, that's for sure. They don't just 'work'

night harness
#

forsure, i assume a fair handful of the dynamics are straight up hardcoded to, no?

#

eg. some of the brimstone patterns

solar jungle
#

What I found was that there are 3 main item types that I could extend the way I need

Coin - picking up increments a value
Boost - stored in active slot, manual use
Equipment - a prefab item, like a gun or a hardcoded body modification

its very easy to come up with a lot of other items just from those 3 things, and it also separates a lot of specific behaviour between them

latent latch
#

Path of exile is a better example of some modular system, but even that game has a bunch of edge cases

solar jungle
#

problem is ive been doing this approach for quite a while now, that i worry ive convinced myself that its the best and only way i can do this

solar jungle
latent latch
#

Well, let's talk about modifiers. Isaac there's a bunch of on hit effects so you'd have a list for each of your weapons like:
List<TriggerOnHit> OnHitTriggers;

So when your weapon hits an enemy you'd cycle through the OnHitTriggers and have like a polymorphic call such as
Trigger(Vector3 position, Entity target)

#

You don't care what the trigger is, you just care where it happened and the target it has hit so now you can invoke it with what information it was given.

steady bobcat
#

usually id say an event is better for anything to get notified of some thing happening but depends if you wish to return something

#

e.g. public event Action<Vector3> OnWeaponHit

latent latch
#

Right, sending some sort of callback too is nice. I sometimes pass the source too instead of invoking a callback

solar jungle
#

Any thoughts on how to deal with a weapon and a projectile being two different things? or even if they really should be?

night harness
#

well first off both are just a damage source

latent latch
#

I've made a system before where everything was a projectile. Need a lingering area damage effect? Projectile with 0 movespeed

solar jungle
#

Thats going to be the plan if I figure out if implementing melee type weapons could work

night harness
#

imo you should make something that they both utilise and/or implement

#

especially if you want more abstract concepts like a radius that damages things inside of it or etc.

solar jungle
#

previously I had a generic bullet that would read a template from the weapon (mostly just to get a damager value)

solar jungle
#

surely they are too different to have much in common

night harness
#

They are both different in a lot of ways but you wanna focus on what they have in common, which is that they both create a resulting piece of data that is sent to whoever is receiving the damage. This piece of data could be the same concept utilised by both DamageSource’s

solar jungle
#

do you mean that the hit info should send more than a basic damage value, but also the weapon along with it?

#

which actually means every bullet is basically just the weapon itself

pliant silo
#

I have a script for generating a mesh of a circle below an object. It currently is generating the mesh not below the object. it is either off to the side, below, or above the object depending on which object it is. I cant upload it all into the file so i sent a screenshot.

#

its all in there

latent latch
#

I've tried the super class idea and it works despite everything be coupled closely together, but it deals with a lot of comparison logic. It wasn't too bad of an idea, but the worst part was trying to make it look good in the editor because the tools for these types of classes is non-existant.

flint dagger
#

Could this warning cause any issues? No matter what I do I can't seem to get rid of it.

solar jungle
night harness
#

The HitInfo doesn’t need to have the damagesource directly referenced but a sword and a projectile are the same in the sense that they are just something that produces a hitinfo, just like any environmental hazard like a spike trap etc.

Having this kind of HitInfo middlemanning the conversation between the damage source and damage receiver allows you to control how much information the recipient gets to know.

For example (this might not relevant for the game your specifically making). If you hit an enemy with an electric sword and they are some water enemy who is weak to electricity, they don’t need to know it was an electric sword they just need to know it was an electric damage source. So the sword could convey that information to the hitinfo

#

What is a super class?

latent latch
#

This monstrosity

night harness
#

ohhhh

#

my comparable experience with that kinda thing would be how source engine does a lot of it's stuff

latent latch
#

reason why I hate the shuriken particle system too

proven talon
#

I have a problem.

#

The character doesn't move

#

Here is the code

rigid island
tawny elkBOT
proven talon
#

ok

steady bobcat
pine spire
# solar jungle do you mean that the hit info should send more than a basic damage value, but al...

The way I’ve often seen this sorted out is some generic damageable interface and different weapons use this to communicate with damageable things. Doesn’t matter if it’s projectile, melee weapon or lava pit. Of course there will be some generic HitInfo too, but when you need something more special it’s easier to expand this. Less need to create some complex megaclasses with gazillion booleans or other conditions

And no matter what kind of system you use, just damage values wont be enough anyway, unless everything uses same vfx and sfx.

lean sail
#

Read the server rules, decompiling/modding help isnt allowed here

twin badger
#

ight

flint dagger
#

I keep trying to add in things to make sure there aren't too many indicies for the verticies but nothing ever works. The point in the function where an out of bounds exception happens can change but it never goes away. Idk what I'm just too dumb to understand but there has to be something fundamentally wrong with how I'm doing this right? Or something obvious I'm overlooking?
The current out of bounds issue is on line 58 in blazebin.
https://paste.mod.gg/zcmzboovagpe/0

cosmic rain
cold parrot
flint dagger
flint dagger
lyric veldt
#

so i'm not too sure whats happening

#

heres the gun code

soft shard
# lyric veldt so i'm not too sure whats happening

Based on your Gun script, it looks to me that you could be calling your Shoot function very frequently (assuming PlayerShoot.shootInput happens while the key is still held down, as opposed to activating once on a single press) - based on your output showing your else log, your calling PlaySound very frequently, which looks like it just does a PlayOneShot, which has no knowledge of any already-playing audio - I would suggest to either use Play and a if-check to see if the audio source is still playing, or add a cooldown based on the audio clip length before calling PlayOneShot again

lyric veldt
#

i just realized that

#

it works now!

native turret
#

can someone explain to me why when i try use rb.velocity unity tells me to update it after i save it which then auto's it to rb.linearVelocity??

#

im trying to make a sprite box jump when i hit space, but rb.velocity doesn't work and when i say yes to update it rb.linearVelocity doesnt work either?

#

nevermind

#

i fixed it

quick token
crimson plaza
#

Is it possible to use C#'s reflection magic to create state machine graphs from code? As in the connections and what not

#

Or is this trying to do things the other way around, aka usually you use nodes and graphs to determine statemachine behaviour

quick token
#

reflection magic?

#

although i am kind of curious too. not sure how to do it myself. you'd probably need an editor extension, but having graph connections in the inspector would make things like dialogue trees a lot easier

native turret
patent kayak
#

is there a better way to check for collisions?

    private void OnTriggerEnter2D(Collider2D collision)
    {
        GameObject collider = collision.gameObject;

        switch (collider.layer)
        {
            // Score
            case 3:
                _score++;
                _onScoreChanged?.Invoke(_score);

                // Disable so it cannot be triggered twice.
                collision.enabled = false;
                break;

            // Pipes
            case 6:
                break;

            default:
                return;
        }
    }
#

i suspect this will get really bad when i do a "bigger" game

leaden ice
patent kayak
leaden ice
#

It's not even clear what script this is or what object it's attached to or what it's doing, etc.

patent kayak
#

imagine if i have like 10 layers

leaden ice
#

not your code

night harness
#

Depends on a lot of stuff but usually you would be checking for a tag or component on the incoming collision to see what it actually is. Then using the layer interaction matrix to naturally filter what could even show up in your results

patent kayak
#

i should have worded myself better: does unity have a way to check if a SPECIFIC layer collided? like instead of checking each collision and filtering by layer, i was qondering if theres something like an UnityEvent or something

#

thats in my player.cs file

leaden ice
patent kayak
#

and it can collide with a bunch of things

patent kayak
night harness
#

you can use the interaction matrix to decide what collisions can happen, you cannot recieve collision callbacks on entire layers though

patent kayak
#

isee

#

im not very good with collisions, in my own engine my collision code was just a huge if kekw

#

and i never even implemented raycasts

leaden ice
#

you don't need to implement collisions or raycasts, the engine provides those for you.

patent kayak
#

yeah i know, i was talking about my own adventure with implementing them in my own engine

night harness
#

an example from something random i have of a more ideal way would be lets say you have a player and theres various interactable objects in the level. the player walks into triggers on those interactable objects to be in range which would look something like

PlayerController

    OnTriggerEnter(Collider collider)
        if (collider.TryGetComponent(out InteractableBehaviour interactable)
            //some logic

This code avoids layers and tags entirely, using a component on the incoming object instead to use as identification and further logic. Butttt we still want to accurately layer all our objects because of the collision matrix. Because these interactablebehaviours only care about the player walking into them for example, we can use the matrix to disable collisions between an Enemy layer and the Interactable layer entirely, because we know we are never interested in checking for that usecase

mild coyote
#

wait, since when when works in unity too? TIL

case AttackDirection.DOWN  when breakDown.Length > 0 ```
vestal arch
#

btw you can use single backticks to get inline code like this

leaden ice
mild coyote
vestal arch
#

this is a language thing

vestal arch
leaden ice
#

oh sorry

#

it's almost 5am

leaden ice
#

this is a switch expression lol

vestal arch
#

linq is for enumerables

leaden ice
#

yeah - I need to sleep

#

I saw when and my brain said where

vestal arch
#

lol

vestal arch
mild coyote
vestal arch
#

it's a csharp thing

#

not a unity thing

#

unity doesn't handle it

mild coyote
#

ah, because I said "in unity too?"

vestal arch
#

c# - or more accurately, the compiler/runtime, mono - handles syntax

mild coyote
vestal arch
#

just making sure you aren't taking away a flawed understanding of what unity actually does

crisp flower
#

what are the main methodologies for handling progression game data? For example, having upgradeable units, tech tree etc... take for example a units speed and accuracy, which over the course of the game can have multipliers etc. applied to it... so from then on all instances of that unit use the final updated value etc.... Whilst giving easy access to everything for balancing etc

stable tapir
#

chat, if i made a matrix/table having lets say photos, and the names within it match a bunch of layermasks, will it work to navigate between teh matrix content from raycasting the layermasks?

quick token
#

dont crosspost

cosmic rain
stable tapir
hexed pecan
#

You posted in unity-talk too

#

Also this is not twitch chat

stable tapir
#

only here and there

stable tapir
merry lodge
#

what channel can i talk abt a problem im having with unity in?

stable tapir
quick token
crisp flower
cosmic rain
quick token
stable tapir
#

using raycast

cosmic rain
quick token
stable tapir
#

the massive storing variable, that stores a bunch of items within it

cosmic rain
quick token
#

there's a lot of ways to store variabels in unity. i dont think a matrix is one of them

stable tapir
#

i said matrix cause ion know the name in english, but i know matrix is the number storage system, and said someone will figure what i meant

tawny elkBOT
stable tapir
#
GameObjects[] objs;
``` is the right way right
swift falcon
#

Hi, two questions how can I fix when it hits the ground, it get kind of stuck for a few seconds and how do I make it when it hits the wall it starts climbing it?
the wheel colider it's in the front wheel

quick token
#

not with the wheel collider atleast lol

#

iirc, the wheel collider uses transform.down. it doesn't actually apply forces based on the wheels full body

#

you'd have to do some weird force shenanigans. probably using the normal of the surface

swift falcon
#

I did, got ignored

quick token
#

well, its only been a few minutes. the peopel who are generally active in the channel are probably asleep or busy. give people some time to get to it CloverThumbsUp

dusk apex
swift falcon
#

maybe?

stable tapir
#
  RaycastHit Hit;
   Debug.DrawRay(cams.transform.position, cams.transform.TransformDirection(Vector3.forward) * 5, Color.green);
   if (Physics.Raycast(cams.transform.position, cams.transform.TransformDirection(Vector3.forward), out Hit, 5, interactable))
   {
       if (Hit.transform.tag == "Chair")
       {
           ItemDetect.texture = images[1];
       } else if(Hit.transform.tag == "Table")
       {
           ItemDetect.texture = images[0];
       }
       else
       {
           ItemDetect.texture = images[3];
       }
       
   }
#

@cosmic rain ik this is the worst possible way i couldve achieved what i want, but why does it not return the image if its not looking at anything

vestal arch
vestal arch
stable tapir
vestal arch
#

matrices are 2d

stable tapir
#

i had to ask chat gpt what was it called

quick token
vestal arch
cosmic rain
vestal arch
stable tapir
#

any idea to replace them ifs cause its gonna be missy with alat of them

vestal arch
cosmic rain
stable tapir
#

one other thing now, why cant i register TMP from the editor interface

quick token
stable tapir
cosmic rain
stable tapir
#

you dont get what i mean, it works perfectly rn, but a bunch of ifs will be missy and annoying, is there anyother way to achieve this

quick token
#

!learn (guh, forgot the command)

tawny elkBOT
#

:teacher: Unity Learn ↗

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

quick token
#

you seem to be unaware of some of the basic terms used in unity

stable tapir
#
  [SerializeField] TextMeshPro ItemName;
``` so i cant register it from the interface
cosmic rain
vestal arch
stable tapir
quick token
cosmic rain
vestal arch
#

structures generally store values

stable tapir
quick token
cosmic rain
vestal arch
stable tapir
stable tapir
cosmic rain
# stable tapir

Now enable a debug inspector mode and look at the actual type name.

quick token
quick token
# stable tapir

like i said above, you're using the wrong TextMeshPro in the script

#

its TextMeshProUGUI not TextMeshPro

#

the naming is a little confusing, but yeah you just need to replace that

cosmic rain
#

You can use a base class of all text mesh pro text components TMP_Text

stable tapir
rigid island
#

never do I type TextMeshProUGUI anymore..

#

TMP_Text much easier and quicker to write, also works for multiple UI and Non-UI

quick token
#

huh, neat, never realised you could do that

stable tapir
#

now i am stuck mentally, i am lost about what to do next

remote kraken
#

I'm on like, my third rewrite attempt of an inventory system that does everything I need, and I wanna smack my head against my desk lol

#

Think this time should probably make a proper list of things to implement rather than blindly coding

lean sail
wheat spruce
#

Does unity 6 have a setting that can enable hot reloading? When I worked in 2022, its possible to save a script during playmode and it applies my changes, but for some reason that isnt happening now

#

Annoyingly any search for "hot reloading" only brings up links to an asset of the same name, so its hard to find relavent results

open plover
#

What is the formula for Unity’s HDR color intensity? I want to set a material’s intensity from script

open plover
#

No I tried that

steady bobcat
#

you mean you want to set a material value via code?

oblique spoke
open plover
open plover
rigid island
#

maybe its a Color4?

steady bobcat
#

shader sources are avaliable so you can probably find what it does specifically

rigid island
#

its been a while since I touched it

#

I just remember when I did it on material color * intensity always worked

open plover
rigid island
#

cause i thought intensity read all the values above 1

#

maybe cause I was using SetColor I think that clamps and reads the rest s intensity ? its been a while lol

wheat spruce
open plover
#

I’n using setcolor as well idk

leaden ice
oblique spoke
open plover
oblique spoke
#

I believe Unity should by default stop play mode and compile

open plover
#

I printed A specular color with an intensity of 5.5 to see how unity handles it

leaden ice
#

Isn't that just a Color in code?

wheat spruce
oblique spoke
wheat spruce
#

aah!

steady bobcat
#

dont bother

#

3rd party plugins to do real hot reload are actually decent

open plover
leaden ice
#

There's no type called HdrColor

open plover
#

Yes

#

I’m editing a textmeshpro’s local lightning color, which has an intensity value

#

I looked at the properties and found only _SpecularColor

#

Which means intensity is somehow inside the specularcolor

#

Cuz there isnt a _SpecularIntensity property

wheat spruce
#

but its sorted now

steady bobcat
#

Id like to use the good hot reloading though but need to ask to have it purchased

oblique spoke
steady bobcat
#

Yea i think only serialized vars get "restored" but ofc the rest of managed memory is lost

swift falcon
#

hey guys i just got here. working on a science project using the UI system (bad idea i know) I've spent hours on google and the documentation and i am so close to giving up where can I find help

wheat spruce
#

I just mean I could alter a simple like like PlayerHealth -= amount; to be PlayerHealth -= amount * 2f; if I quickly want to test something out

#

I dont rely on it in order to work, but the convenience it brings for some quick changes without needing to exit and enter playmode, is nice

vestal arch
oblique spoke
soft shard
# remote kraken Think this time should probably make a proper list of things to implement rather...

Making a list of how you want a feature to work is a big help, rewrites happen even with a plan (sometimes for optimization other times for readability/organization) though I found thinking of things in a data-driven way helps me - so ill first think about the most common functionality, then what data or references/dependencies are needed to build that functionality and how I might use that data (can it exist as a serialized class? Should it be a scriptable object to be reused? Do I need to save it to a file?) - then ill think about how to separate the core system (such as managing a list of "slots") and the gameplay features (such as maybe what those slots will accept, like specific "item types") - then I can start thinking of how ill actually build it, which for me is often deciding what patterns make the most sense to use, that way if things change, its not a total rewrite, and adding or removing features is often managing the patterns I chose to use

wheat spruce
swift falcon
#

is there a help forum?

soft shard
vestal arch
steady bobcat
swift falcon
swift falcon
vestal arch
#

this isn't the general channel, this is a code channel

#

but if it's code related, sure

swift falcon
#

ok

wheat spruce
vestal arch
#

!ask

tawny elkBOT
steady bobcat
oblique spoke
wheat spruce
#

ah, well in that case I have found in the past it feels like it drops changes that really should have been applied

swift falcon
#

So here's the problem: I am making a gamified task tracking app to track carbon footprint. I am using a UI image as the task button. it opens an overlay based on a specific string stored inside the object. When I instantiate the task, it is unable to store a string and then I am unable to pull the string to open the overlay.

open plover
steady bobcat
tawny elkBOT
wheat spruce
#

if I know a change I'm making is more likely to not count, thats when I just exit playmode like normal

minor swan
swift falcon
#

should I ask in another chat I feel like i'm interupting

swift falcon
open plover
#

If ur using the old UI system, it should be easy

swift falcon
#

nothing is easy when instantiating

vestal arch
#

that doesn't actually answer that question

steady bobcat
#

SHARE YOUR CODE FIRST

#

asking pointless questions is confusing em

open plover
#

No I mean are you putting buttons and texts in your scene from the inspector or are you using the UI document

swift falcon
#

I'm trying to figure out how to share it well without dumping like, 6 pages of code gimme a sec

soft shard
#

In Unity, there is "UI Toolkit" which may be the "new" UI system, and the "Canvas" which may be what you would find in the manual at first

swift falcon
open plover
#

Then it should be relatively easier. What problem are you having to be exact?

steady bobcat
#

@swift falcon can you share your code specifically where you try to open this other UI and interact with your "new task instance"?

swift falcon
steady bobcat
#

šŸ‘

swift falcon
#

ok so its like three scripts interacting how u want me to do this?

steady bobcat
#

well you know what problem you specifically have so show the parts we need to see (e.g. where you open this new UI and try to give it data)

swift falcon
#
    public static int TransformCount;
    public int TransformYvalue;
    public void CopyTask(string NewTaskData)
    {
        //do not fix or TOUCH AT ALL if this is touched everything breaks!!!
        //do not optomise in fear of project collapse
        TransformYvalue = TransformCount * -150; //makes distance farther for every new task
        GameObject newbutton = Instantiate(buttonPrefab, new Vector3(0,TransformYvalue,0), Quaternion.identity, buttonParent.transform);//creates new button
        newbutton.gameObject.GetComponent<ThisoneVariable>().BString = NewTaskData;
        TransformCount ++; //increases distance for next
    }
steady bobcat
#

wait you are trying to put multiple bits of data into a string?

swift falcon
#

its one string

steady bobcat
#

just make a class /monobehaviour to store all your info for a "task"

swift falcon
#

that is one example

steady bobcat
#

yea dont do that

swift falcon
#

what is the better way then so each instantiated object has it's own three bits of data that can then be pulled by another script

steady bobcat
#
public class TaskData
{
  public DateTime creation;
  public string name;
  public int order;
}
#

you need to go learn c# basics if a class is a new concept to you 😐

swift falcon
steady bobcat
#

haha are you sure

swift falcon
#

it was a while ago and then i didn't use it for a while... i forgot way too much

#

i'm sorry.

#

how do I call the class in my script?

#

the way i'm doin it right now is... overly complicated

#
    public void OpenOverlay1FromInspector()
    {
        GameObject ClickedTask = GameObject.FindWithTag("TaskClicked");
        string messageAndPoints = ClickedTask.gameObject.GetComponent<ThisoneVariable>().BString;
        //^^^finds task that was clicked and takes it's string
        string[] splitData = messageAndPoints.Split('|');
        string message = splitData[0];
        int points = int.Parse(splitData[1]);
        string link = splitData[2]; //should set 3rd split value to link
        OpenOverlay1(message, points, link);
        ClickedTask.gameObject.tag = "Untagged";//untagges tag
    }
steady bobcat
#

A MonoBehaviour is a class so give it your data how ever you want.... Via a function or public field or property.

#

GetComponent<TaskDisplay>().ShowTask(new Task());

swift falcon
#

yeah no i suck at C#. I can't remember things at all so i'm bad at doin this kinda stuff sorry

steady bobcat
#

Then revise the basics there are plenty of good resources out there

swift falcon
#

thanks for helping i've spent many hours trying to figure this out on google and in the documentation

steady bobcat
#

Well unity docs won't cover c# language things as it doesn't need to. Check the Microsoft c# tutorials

swift falcon
steady bobcat
#

well if you have a class that holds "task" data then your ui that shows this can be given any instance.
If you need it to be stored on disk for later use then have some save class to hold a list of em:
List<TaskData> allTaskData;. You can use the unity json serialization stuff to easily save/load most data from disk.

#

use json.net for a better json serializer that supports more types

swift falcon
steady bobcat
#

An ideal overview of the app would be on open it loads the saved task data. Each task can have a unique id and you can render a list of all tasks in the UI. The user can click one to view more info and edit a task. They can save the changes and close the window. The user can save all tasks to disk again. Rinse and repeat

remote kraken
swift falcon
remote kraken
#

I don't know why I tend to use one of the hardest things to code when learning a language xD

steady bobcat
lean sail
swift falcon
#

bonjour. Ca va?

steady bobcat
#

Server is English only

swift falcon
#

je parle petit france

lean sail
#

its really like 5 lines of code

stable tapir
#

can someone explain to me how does rigidbody.drag works

swift falcon
lean sail
#

!collab

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs

lean sail
#

read the server rules dude

swift falcon
#

u should prob delete it too

#

no?

#

its against server rules and keeping it up is kinda not the best. might get u banned if u keep it up intentionally, just a friendly warning

#

i am not very good at french lol

lean sail
#

again read the server rules, off topic chat is not allowed

swift falcon
lean sail
swift falcon
vestal arch
#

like, in physics

swift falcon
#

i cant even see rigidbody.drag in the documentation

vestal arch
#

it's not called drag in v6

lean sail
swift falcon
vestal arch
swift falcon
#

@lean sail u have a sec to help me a tiny bit more to understand how I should use this in my circumstance?

lean sail
#

šŸ¤·ā€ā™‚ļø have you tried using it

soft shard
# remote kraken I tend to think that with other languages I know, but I don't know C# well yet, ...

If you feel you are a bit unfamiliar with C#, I would suggest trying w3schools: https://www.w3schools.com/cs/index.php - they have great sandbox-like lessons to learn and practice, then maybe you could try focusing on specific topics that challenge you - if you feel familiar with that content, I would suggest maybe learning about code patterns in C# - Jason Weimann, Infallable Code, git-amend and Terodev are great channels imo that go over using C# patterns in Unity - maybe some of those suggestions could interest @swift falcon as well

swift falcon
swift falcon
#

once again, I'm not good at this. I'm just trying to scramble by on the information I have and with many many iterations, but I'm running out of time and am starting to freak out that I might not have this done on time

soft shard
swift falcon
swift falcon
soft shard
# swift falcon it is C# but I was too broke to afford pro to do the projects

You could also try Github, there are lots of free projects to learn from there, including Unity sample projects, the nice thing with Unity is there are lots of resources like blogs and YouTube channels that cover code-alongs and examples of different approaches in Unity (such as using ScriptableObjects as an example)

remote kraken
soft shard
# remote kraken I've been looking through it, typically my go to site for coding related informa...

Maybe this video could help? https://www.youtube.com/watch?v=YEk7mKovpUE - it explains how Unity handles references, though in a simple example, everything works with objects (OOP - Object Oriented Programming), so if you want to access data from another class, you need to know where that other class exists, and thats often done by having a "reference" to it either through the inspector, or through code with Unitys API - though its usually good practice to cache that "reference" in a variable if you use Unitys API such as GetComponent

A few basic ways to get references in Unity.

Directly-
GetComponent 0:38
/GetComponentInChildren
/GetComponentInParent

Public Variable- 3:00

Find- 5:01
Find 5:39 (by name)
FindWithTag 6:14 (by tag)
FindObjectOfType 6:51 (by component)

Interaction- 7:15
OnCollisionEnter
/OnTriggerEnter

ā–¶ Play video
stable tapir
lean sail
lean sail
swift falcon
lean sail
#

im not sure what you're referring to at all "when the thing is copied, it doesn't write correctly". if you're talking about that old code you wrote above, yes you shouldve just started rewriting it by now

vestal arch
swift falcon
#

heres the full error

#
NullReferenceException: Object reference not set to an instance of an object
ModalWindowController.CopyTask (System.String NewTaskData) (at Assets/Scripts/ModalWindowController.cs:114)
heady iris
#

proper air drag is proportional to the square of your speed

vestal arch
heady iris
#

I believe the linear damping is linearly proportional

vestal arch
#

something's null in that line

heady iris
#

so 10x speed means exactly 10x the opposing force

#

rather than 100x

vestal arch
heady iris
#

I haven't carefully tested it, though

swift falcon
#

newbutton is defined by this:

GameObject newbutton = Instantiate(buttonPrefab, new Vector3(0,TransformYvalue,0), Quaternion.identity, buttonParent.transform);//creates new button
vestal arch
#

it's probably the GetComponent then

swift falcon
vestal arch
#

check if buttonPrefab actually has that Thisonevariable component

#

try debugging stuff in the code, like right before that line with the NRE, do Debug.Log(newbutton); etc

swift falcon
#

it does have it, but for some reason i think it cant find it?

vestal arch
#

also if you don't need anything else from the newbutton, you could type buttonPrefab as Thisonevariable, then newbutton would also be a Thisonevariable and you wouldn't need the GetComponent at all

#

hey wait a minute

#

those are different newbuttons

#

GameObject doesn't have a gameObject property

#

can you show the full file? see below
!code

tawny elkBOT
swift falcon
#

(for context thisonevariable is a script that only has one line, defining a string so i can save a string to each button instance)

austere solar
#

Help - i have a IEnumerator Start() where i have yield return new WaitForSeconds(2), but when that line is reached, Unity completely freezes up. Doesn't react to clicks, doesn't update, doesn't pop-up those annoying windows when it's saying that you clicking something is somehow a 20 seconds task...

swift falcon
vestal arch
#

once you've saved a paste, yes

austere solar
vestal arch
swift falcon
charred torrent
#

okay so i wam tired of draging and droping refrences into the inspector

#

is there a way to resolve that

vestal arch
#

huh, ok. so apparently GameObject does have a gameObject property, it's just undocumented lmao

#

resolve... what, exactly?

swift falcon
naive swallow
vestal arch
#

that was asking demigod, not you

austere solar
# vestal arch can you show some context? (see the above embed)
// Start is called before the first frame update
public IEnumerator Start()
{
    paused = true;
    LevelData currentLevel = LevelData.CurrentLevel;

    //... Some code ...

    Debug.Log("Assigned files");

    // spawn first notes
    notemanager_script.ManualUpdate(0);

    Debug.Log("Created first few notes");

    yield return new WaitForSeconds(2);  // <---- Here

    Debug.Log("Waited for 2 seconds");

    StartCoroutine(LoadingScreen.Finnished());

    Debug.Log("Closed the loading screen");

The last line i see in Debug is Created first few notes. Than unity completely freezes up, like im looking at a static image and not a program window. Zero response.

swift falcon
vestal arch
charred torrent
# naive swallow No, that is the correct way to do things

i also dont want to write it in awake cuz then it is gonna run everytime i start the game
is it possible that it just stores the refrence there forever once after i start the game cuz write now it loses the reference once i stop the game

vestal arch
#

yeah i don't think that works

#

make a separate coroutine that you initialize from Start

charred torrent
#

that also reduces performane bro getcomponent is heavy task

vestal arch
austere solar
naive swallow
vestal arch
naive swallow
vestal arch
vestal arch
#

it does? damn

charred torrent
austere solar
#

Yeah, this isn't the only one i'm using. This is the first one causing troubles.

naive swallow
vestal arch
# naive swallow It does

out of curiosity, does that also apply to other messages? awake, onenable, update/lateupdate/fixedupdate...

swift falcon
vestal arch
swift falcon
#

degug log after instantiate or before?

naive swallow
rough sorrel
#

Hello. This might be a vey basic question, but if I have a list that is

private List<Matrix4x4> matrices = new List<Matrix4x4>();

why is it that doing

matrices[i].SetColumn(3, origin);

is not the same as doing

Matrix4x4 matrix = matrices[i];
matrix.SetColumn(3, origin);
matrices[i] = matrix;

? Like with the first option nothing changes in that Matrix4x4, but with the other option it correctly changes the value

vestal arch
swift falcon
#

nothing

vestal arch
#

did you save and recompile

swift falcon
#

yes

rough sorrel
swift falcon
#

nothing except for the same error as before. line is 115 now, but that's b/c i put the debug log line in

vestal arch
#

doesn't even count the log?

swift falcon
#

the line of the error was the line after instantiate, which was 114. now it is 115

#

this is inbetween the two:

        Debug.Log(newbutton);
charred torrent
naive swallow
charred torrent
#

just like that but only once maybe an editor script or something like plugin

#

712

naive swallow
#

I'm still not sure what your specific problem is but I can assure you that direct referencing in the inspector is the most efficient and fastest way to reference anything. All other forms of reference should only be used when direct referencing is impossible.

charred torrent
#

i wanna assign the refrence through code i i dont wanna be drag and dropping stuff but i need the performance of drag and droping stuff

naive swallow
charred torrent
#

dont wanna drag and drop cuz there is too many stuff to drag and drop

leaden ice
naive swallow
#

The you'd best get started

leaden ice
#

Use the profiler, you won't even be able to find those GetComponent calls.

charred torrent
#

okay then as you say

#

its a mobile game so i thought best to be otimizing as much as i can

swift falcon
leaden ice
vestal arch
swift falcon
remote kraken
swift falcon
vestal arch
swift falcon
#

debug logged the Y value variable and this popped up

#

so debug works then

#

maybe it's going wrong somewhere within instantiate and therefore won't go past it?

austere solar
charred torrent
#

that makes things easier for myself

#

by not drag and droping things but giving me the performance of it

leaden ice
#

You should start with GetComponent and circle back to the problem if and when there's a demonstrable performance issue (there won't be)

restive canopy
#

alright

#

Ive a bone to pick with C#

#

why is it that I can't get the teleport function to work like its supposed to!?

#

i tried the disabling of the movement script, but it still wont move!

lean sail
#

configure your !ide first

tawny elkBOT
restive canopy
#

course

#

i dont see a difference

rigid island
restive canopy
#

i have it installed

#

aint that enough?

rigid island
spare dome
#

do you have the Visual Studio Editor package in unity and if so did you regenerate project files?

restive canopy
#

thats all the steps I got!

#

just install the mod!

rigid island
restive canopy
#

no i didnt

rigid island
#

so then its not all lol

#

close VS , set the Editor in dropdown. Click Regen Project files button after that too

restive canopy
#

its set the the version Im using

#

and I regened the files

#

nothing

rigid island
restive canopy
#

yes

rigid island
#

screenshot solution explorer in VS

mossy oyster
#

Might not be code but does someone have any idea why enabling shadow cascades mess up the sorting or trails? I can see in the editor they are above a plane, but when testing the game, they are under it (moving them up a bit fixes the problem but lower quality settings don't have shadow cascades so it won't work)

restive canopy
rigid island
#

neither of those are VS

restive canopy
#

what do you mean solution explorer?

rigid island
#

View -> Solution Explorer

restive canopy
#

all I got is the unity code assist

rigid island
restive canopy
#

colors are right again

#

as I was saying

#

i cant get this pricking player to change position

rigid island
#

so is the log printing ?

restive canopy
#

iyes

rigid island
#

what is PlayerHall

restive canopy
#

the transform.position is not doing anything

#

movement script

rigid island
#

so its not the controller?

#

which controller are you moving with

#

in PlayerHall

restive canopy
#

HallwayPlayerMovement

restive canopy
rigid island
#

are you using rigidbody or cc

restive canopy
#

Oh Rigid Body

#

... Wait I just use THAT to move?

vestal arch
#

yeah

#

rigidbody does physics

restive canopy
#

All the other stuff from forums before coming here just said


transform.position = GameObject.transform.positio

vestal arch
#

you can apply forces or set velocity

heady iris
restive canopy
#

This makes no sense at all

#

HOW IS IT THIS HARD?!

austere solar
leaden ice
restive canopy
#

so. the debug log is firing off

#

what isnt happening is the setting of the new position

#

must more blood be shed

leaden ice
restive canopy
#

This is the only bit of code in all the scripts that even involve positions

#

the rest are just enabling of UI elements and movement scripts

leaden ice
#

Well you didn't address the first part of my sentence for one

#

And for two, other components exist besides the ones you wrote

#

And for three, you might be mistaken about that

restive canopy
#

so right now-

#

... if its referencing the script, getting the position of the object isnt gonna do anything, is it

leaden ice
#

I don't know what you mean by that

restive canopy
#

the floorXDoorX objects are looking for the scripts of the objects

#

not the gameobject themselves

leaden ice
#

It depends on, ultimately, which object this chain of references is referring to

heady iris
#

what you're calling "scripts" are components, and every component is attached to a game object

leaden ice
#

It's referring to instances of the scripts that are attached to the actual GameObjects

#

The question is WHICH ONES

restive canopy
#

they're pointing at the component of the door gameobjects that allows me to even interact with them

#

and once I am in range and hit E, it should make it so that the player teleports to the other door

leaden ice
#

Oh gosh

#

I'm talking about this PlayerPawns.PlayerHall.rb thing

restive canopy
#

oh

#

thats tallin about this

leaden ice
#

Sure but what are the references assigned to?

restive canopy
#

... it may just be pointing at the scripts and not the object holding it...

#

oh i am a brilliant moron

#

mystery solved

#

thank you for your time

leaden ice
#

It's neither of those things.

It's an INSTANCE of the script

restive canopy
#

so before I just dragged the script from the assets folder into the thing

leaden ice
#

That wouldn't work

restive canopy
#

when what I shouldve done was just drag the object holding the script component and make em work

#

badda bing badda boom, solved

heady iris
#

what you're describing is either wrong (if you were dragging in a prefab asset with the relevant component on its root object) or impossible (if you were dragging in a script asset)

glacial swan
#

whoops lemme rename file

glacial swan
glacial swan
#

thank u

solemn ember
#

sup gang

#

is there any way I can make enums inherit like this?

#

that way I can keep calling my "PlayAnimation" like that

#

I would love to encapsulate my weapon animations in different structs, I believe

#

I assume I should switch to dictionaries šŸ¤”

#

because in the long run, when I have more than 10 weapons, it will be a mess

sullen urchin
# solemn ember

Tutorial of how to manage animations entirely through script in the Unity game engine!

Tired of struggling with the Unity Animator? In this tutorial, I'll show you how to create smooth and efficient animations entirely through scripting, eliminating the need for the Unity Animator once and for all! Say goodbye to clunky animations and hello to ...

ā–¶ Play video
#

if not forget it šŸ‘€

cold parrot
errant flame
#

Hi, I have a problem with the object pool class, I have two different pools in 2 different classes, I run the pool.Clear() method in both of them and the implementation of both is the same.

One of them sends all the created objects back to the pool and clears the objects, while the other does not clear the objects and does not give any error.

What could be the reason?

#

An example how i implement that two pools

            _tilePool = new ObjectPool<GameObject>(CreateTile, GetTile, ReleaseTile, DestroyTile, true, DEFAULT_POOL_CAPACITY, POOL_MAX_SIZE);


  private GameObject CreateTile()
        {
            GameObject tile = Object.Instantiate(DataStorage<AddressableResource>.Instance.ScoreHolderTilePrefab, View.ScoreHolderRectTransform, false);
            RectTransform rectTransform = tile.GetComponent<RectTransform>();
            GridData scoreHolderGridData = _scoreHolderGridSystem.Controller.Data;
            rectTransform.sizeDelta = new Vector2(scoreHolderGridData.CellWidth, scoreHolderGridData.CellHeight);
            return tile;
        }

        private void GetTile(GameObject obj)
        {
            Debug.Log("Getting tile");
            obj.SetActive(true);
        }

        private void ReleaseTile(GameObject obj)
        {
            Debug.Log("Releasing tile");
            obj.SetActive(false);
        }

        private void DestroyTile(GameObject obj)
        {
            Debug.Log("Destroying tile");
            Object.Destroy(obj);
        }
weak venture
#

will i hit a perf penalty from instantaiting a prefab one shot particle system vs holding one and calling emit on it?

lean sail
errant flame
#

m_List count its 0 but there are elements from pool on scene how can that possiable xd

lean sail
errant flame
#

i got it

lean sail
#

did you maybe just not have any objects in the pool?

errant flame
#

i have non released objects in one pool its when i call clear it doesnt do anything but i store the collection of when i get obj from pool .

first if i release one by one all of them then they will be still in scene with non active objects after then i call Clear its worked

#

Its only clears non active released objects i guess

wraith cobalt
lean sail
#

šŸ¤” i dont get what the title of that video means, i skimmed through the video and they're literally using the animator the entire time

fervent juniper
#

Hi guys, i was seeking some help regarding a game mechanic of my game, im replicating the game called brawl stars, and was trying to make the game mode called brawl ball, but im currently struggling with the mechanics and physics around it, such has having a rigidbody on the ball is messing with the player. Currently the ball it self is without a rigidbody, I have 2 colliders on it, one which is isTrigger and slighter bigger radius so it doesnt fall through the floor. Code wise its currently like this

void OnTriggerEnter(Collider other)
    {
        PlayerController player = other.GetComponent<PlayerController>();

        if (player != null && !isHeld)
        {
            if (player == oldHolder && travelledDistance < 0.5f)
                return;

            PickupBall(player);
        }
        else
            PickupBall(player);
    }

public void PickupBall(PlayerController player)
    {
        if (isHeld) return;

        holder = player;
        isHeld = true;
        transform.SetParent(player.ballHolder.transform);
    } 

 void Update()
    {
        if (isShot)
        {
            transform.position += currentVelocity * Time.deltaTime;
            travelledDistance = Vector3.Distance(shotStartPosition, transform.position);
            if (Vector3.Distance(shotStartPosition, transform.position) >= maxTravelDistance)
            {
                StopBall();
            }
        }
    }

one thing i was struggling is when the ball is shot backwards, it re triggers with the same player, but continues to move so its attatched as a child again, but the ball doesnt stop moving so its a mess, if someone could direct me with the right approach to a proper picking up and shooting mechanics, would be awesome!

dusk apex
fervent juniper
dusk apex
#

As for stopping, when should it stop? When held?

#

If it only stops when it's picked up then perhaps it isn't being picked up.

#

If so then you'd check on the conditions for it to be picked up.

dusk apex
jade cloak
#

do yall know how to apply decals in cs code?

#

only way i could find is with the weird component

fervent juniper
# dusk apex As for stopping, when should it stop? When held?

What I meant was lets say I shoot the ball, if i shoot it backwards, it re-triggers the OnTriggerEnter, which is an issue hence why I added the travelledDistance check, not sure if its a good method but it works ig, my current issue with this obviously if I use a rigidbody, it moves the player as well. This also happens without a rigidbody, I can upload a video if you like. but I do need a rigidbody for stuff like bouncing off walls and stuff like that. I dont think I can implement that kind of stuff without it..

dusk apex
soft shard
# jade cloak only way i could find is with the weird component

Unity has a built-in "Decal Projector", and in HDRP there is a Decal shader, otherwise if your using URP, you may need a custom shader AFAIK, though what do you mean by "apply"? Are you trying to set a existing decal to a specific texture or instantiate a prefab with a decal component already attached or enable and reposition a decal that already exists in the scene or something else?

pure ore
spark stirrup
fervent juniper
#

If a user catches the ball which was bounced off the wall, it messes up its movement, sometimes even moves the player

#
void OnTriggerEnter(Collider other)
    {
        PlayerController player = other.GetComponent<PlayerController>();

        if (player != null && !isHeld)
        {
            StopBall();
            PickupBall(player);
        }
    }

Even though the ball is stopped, then picked up

#

It could be that it doesnt stop fast enough before PickupBall is called perhaps

dense estuary
#

I have an inventory system, in the Inventory class, I have an InputAction method that runs the Use method stored in the currently selected item, then deletes the item if it isn't marked as multiUse.
I have a Hand class which manages the visual representation of the items in the players hand, by instantiating a model as a child to the PlayerHand object.
I want to make it so the item in the current slot only gets deleted after an animation on the model of the item ends.

#

One moment, let me fetch the code.

thorn knoll
#

guys is ml agents worth still learning or is it dead, as you need many old versions of libraries and its so hard just to set up

narrow sapphire
mighty yoke
#

Hey! Im new to coding and stuff but i was just wondering if anyone would be able to teach me how to make a simple fishing sytem and also maybe a inventory system. if not its ok. Thanks!

vestal arch
#

there's existing resources

late osprey
#

Hey y'all. I'm working with getting my movement working using Rigidbodies and AddForce but I've run into the issue with applying force in the direction relative to my player.

I've tried using quaternions to adjust my input vectors MoveDir but to no avail. I know my math is wrong but I'm not sure where I've messed up. Any help is greatly appreciated

Edit: Picture added so it's easier to read

#

Ah I've solved it. I was using a Vector 3 rotation on a Vector 2 lol

spark osprey
#

Hello can canyone suggest any tutorial videos to make a 3d puzzle game in unity i am new to this and i want to make a game project at beginner level for my cllge

real spire
#

The unity API and my own ideas have failed me. I need help or advice please

The short version of what I need is that, when a player uses WASD or a gamepad to navigate menu buttons, the game needs to detect it and update a text box with data relating to that text box. I know the EventSystem within Unity knows what object is currently selected, but I am not sure on what is the best way to go about detecting if that object changes.

I have tried some ways to try and accomplish it but most of them either fail or are way, way too janky to be a reasonable option.

One way I thought of is to have the update constantly have a HUGE Case Switch Statement that checks the names of each of the buttons, but this isn't very dynamic and can be prone to becoming even longer if I need to add more buttons to the menu.

Would anyone who has dealt with this system, and knows a more simpler solution?

late osprey
#

Are you using the (new) Unity Input System?

real spire
#

And it works as intended, my system is able to comfortably control the menu using a Dpad or WASD

#

Basically, the system navigates through a list of moves, and when a new move is selected, I want a description of the move to appear in a text box, if that gives better context.

Note, I don't want the discription to change when you click on the move, I want it to change when that object is now swapped to be the currently selected object within the unity event system

tawdry jasper
real spire
#

Well, this attempt at detection does not work.

_textholder returns as a nullref which means that it is not assigned. Which means that the if comparason did not succeed, and I do not know why XD

#

Wait, no I am a moron, the second statement in the if will never go through as true

#

AAAAAAGH

#

Trying again

#

Nope, still a null ref

tawdry jasper
quick token
#

pretty sure TMP_Text is just the base class of TextMeshProUGUI. i doubt that would cause it

real spire
#

It still causes the null ref.

I'm going to add a few other logs to see where it is not firing

#

Yeah, that if statement is never triggered.

For context, BattleControlSystem.actionTexts are a list of TMP_Text that are stored. The reason is that they need to change depending on the character's move set.

vestal arch
#

where's the nre exactly?

real spire
#

I found the problem, I was comparing the wrong list

#

AAAAG

#

Small mistakes are my greatest enemy

crimson plaza
#

I saw somewhere that suggested using a single script to control a bunch of objects that have the same behaviour was more efficient than each of them having a copy of said script, and was wondering if this was true? For example moving kinematic objects and what not

vestal arch
#

focus on getting something that works and makes sense

swift falcon
#

Unable to get desired values via **Mathf.PerlinNoise **function
I use float parameters
The problem is with scale variable. It doesnt let you control the size of the noise. Basically its all over the place. Using 0.1f is smaller noise than 0.5f, but 0.01f is bigger noise than 0.1f, Doesnt make sense to me

Mathf.PerlinNoise(worldPos.x * scale, worldPos.y * scale) * 2 - 1
vestal arch
swift falcon
#

Is there no simple way to increase noise size?

wheat spruce
#

what do you mean by noise size?

#

PerlinNoise always returns a value between 0 and 1

#

just to confirm, doing * 2 - 1 is going to return a value that is between -1 and 1. Does that sound right for what you want it to do?

swift falcon
#

Yes

wheat spruce
#

as for size, do you mean that perlin creates a full noise result like shown in the red version on the left (yes its you are getting a 1D value, not 2D, but the principle is the same), but what youd want is to actually get a smaller portion of the full texture and use that, which for the blue would mean that you are zooming in

#

because thats what worldPos * scale does

swift falcon
#

Yeah like blue. But i dont feel like i have control over the size. Decreasing/increasing the scale works until it doesnt, at some point it stops getting smaller and gets bigger instead

wheat spruce
#

Hmm, I havent worked with Mathf.PerlinNoise for quite some time, but thinking back to when I did, this does sound familiar

swift falcon
#

Nevermind i projected it onto a texture and it seems to work correctly

wheat spruce
#

let me check out perlin noise, I'm curious to see something

#

well, if unity decides to open

crisp raptor
#

hey how can i make a 3rd person character controller like god of war

#

did

#

cant find anything good

vestal arch
#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

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

soft shard
crisp raptor
#

like "god of war like character controller "

soft shard
# crisp raptor like "god of war like character controller "

Maybe try searching for more general terms, instead of the specific game, try searching the features of a "god of war" character, for example "third person character controller" if your wanting that feature of a god of war character, also adding the keyword "unity" and "c#" can help refine search results

distant stratus
#

hi

sleek bough
#

@distant stratus Don't spam multiple channels. Did you read the bot collab message?

distant stratus
sleek bough
#

!warn 1320795669744844892 Don't spam the channels. Read community conduct.

tawny elkBOT
#

dynoSuccess frank1215000 has been warned.

teal latch
#

Hi I have issue with Unity WebGL I have latest version in Engine but when I package and run it in browser it keeps showing older version even if i remove the cache how to solve this please ?
Using Unity 6

sleek bough
#

Make sure you've deleted old archive, some apps don't replace with new files by default.

teal latch
#

I delete the whole build and make a clean build @sleek bough

#

do i need to remove some files from the Project's folder ?

sleek bough
#

Just build into fresh archive and make sure old one replaced where you test it.

teal latch
#

I'm doing this already deleting the complete old build and build a new fresh one ..
Thanks you ..
But not useful solution 😦
even tried an Incognito browser same

prime acorn
#
public override void OnHoverExit()
{
    if(!someBool) return;
    go.enabled = false;
}

public override void OnHoverExit()
{
    go.enabled = false;
}

I know in this case it is negligible because it only gets called rarely but which approach of the two is better?
someBool is only false when go is already disabled, so all the if statement does is prevent the disabled go from being disabled again in this case.
Therefor my main question is which approach would technically perform better? Asking a bool and then only setting it once, or setting it every time it gets called?

dense estuary
zenith glade
#

Does anyone know what structure the data received from skinnedMeshRenderer.GetVertexBuffer() has? Is it consistent? Is there a method to get it? Thanks in advance

#

I'm trying to get quads to my shader and Graphics.RenderPrimitivesIndexed with MeshTopology.Quads seems the only way to get there, so I have to manually unpack this data in the shader. (It seemed like using Mesh.SetIndices to MeshTopology.Quads didn't work... unless I messed up something else, which may very well be possible)

dusk apex
#

This is a coding channel. You should consider asking in #šŸ’»ā”ƒunity-talk if it isn't a coding question to better acquire help

#

Whatever you do, don't cross post but instead move your post by deleting the post here and posting wherever it needs to be posted #šŸ“–ā”ƒcode-of-conduct

pallid girder
#

Does anyone know why i cant connect to unity cloud or use unity version control?

leaden ice
pallid girder
#

is it not free?

leaden ice
#

It's free

#

You just need to agree to the terms

pallid girder
#

oh

#

thanks it worked

#

ohh letsgoo

#

thank you so much

jade cloak
swift falcon
jade cloak
#

šŸ’€

soft shard
# jade cloak im trying to have a gib that leaves a blood trail on the floor

Im not sure the built in Decal Projector can do that, if your using HDRP, the Decal shader for that pipeline may be able to do something similar, or you could try using a particle system or VFX Graph, otherwise you could likely create a custom shader, if you prefer using ShaderGraph you might be able to find tutorials about drawing ontop of a mesh to create a "trail-like" effect, otherwise if you prefer HLSL/coding shaders, you could look up "Catlike Coding" who may have some blogs about drawing on meshes for a similar effect - there may be other ways too, though atm that is what comes to mind

jade cloak
#

ok ill see if i can

pure ore
#

How can I get smooth gravity? My jumping and gravity seems too jittery to be smooth

    private void UpdateMovement(Transform transform)
    {
        Vector3 vector = transform.right * MovementInput.x + transform.forward * MovementInput.y;
        m_MovementDirection.x = vector.x * CurrentSpeed;
        m_MovementDirection.z = vector.z * CurrentSpeed;
        if (m_CharacterController && m_ActiveGravity < 0.0f)
        {
            m_ActiveGravity = 0.0f;
            m_MovementDirection.y = -0.27f;
        }
        else
        {
            m_ActiveGravity += Physics.gravity.y * m_GravityForce * Time.fixedDeltaTime;
            m_MovementDirection.y = m_ActiveGravity;
        }
        if (MovementDirection.x > 1f)
            m_MovementDirection.x = 1f;
        if (MovementDirection.x < -1f)
            m_MovementDirection.x = -1f;
        if (MovementDirection.z > 1f)
            m_MovementDirection.z = 1f;
        if (MovementDirection.z < -1f)
            m_MovementDirection.z = -1f;
        CollisionFlags collisionFlags = m_CharacterController.Move(MovementDirection);
        if (!m_CharacterController.isGrounded && collisionFlags == CollisionFlags.Above)
        {
            collisionFlags = m_CharacterController.Move(Vector3.up * -0.1f);
        }
    }
soft shard
# prime acorn ```cs public override void OnHoverExit() { if(!someBool) return; go.enab...

Even if this was called very frequently, I would imagine the performance impact to still be negligible, though the performance impact will depend on what the property enabled does in its setter, if its only setting the same value (false in your case) to the same variable, then I believe there is no difference since the memory for that bool would not have changed (although the function call would still reach the stack AFAIK) - however, the first approach could be good if the property does more than just set a variable to a value, or when there is other logic that may depend on the bool being true, so it can be a good fail-safe - though, in practice either approach would be a nearly non-measurable micro performance in the worst case

unreal notch
#

back again trying to solve this issue...

I think I've narrowed down what the problem is, but I'm not sure how to fix it
I am using transform.Translate to move in a controller2D script, but that is not where the issue is

I believe the issue is the way I am applying gravity and maxJumpHeight
during start, I define my gravity and maxJumpHeight based on some predefined numbers and math

        gravity = -(2 * maxJumpHeight) / Mathf.Pow(timeToJumpApex, 2); //g = -a2 / b^2
        maxJumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
        minJumpVelocity = Mathf.Sqrt(2 * Mathf.Abs(gravity) * minJumpHeight);```

then during update, I do a method that changes my y velocity before it is sent to the controller2D
```cs
    public void CapFallSpeed()
    {
        if (velocity.y > maxFallSpeed)
        {
            if (!castingModeOn && !meleeAttacks.upHeavy)
            {
                velocity.y += gravity * Time.deltaTime;
                velocity.y = Mathf.Clamp(velocity.y, maxFallSpeed, Mathf.Infinity);
            }
            else if (castingModeOn)
            {
                velocity.y += gravity / 4 * Time.deltaTime;
                velocity.y = Mathf.Clamp(velocity.y, maxFallSpeed, Mathf.Infinity);
            }
        }
    }```
#

I think the think causing this issue is that my timeToJumpApex isn't compatible with variable framerates
currently, it is 0.4f, and this gives me the perfect jump height at 30 fps, but if my fps is lower, and frames get skipped, I think what happens is
that I am already done with the timer for reaching timeToJumpApex but I'm not getting the +y velocity from the frames that got skipped

i.e.
lets say I get +1 vertical vecocity every frame
if my framerate is stable and constant, after 10 frames I get +10 velocity
great

but lets say I skip 3 frames in the middle... not a problem, cause I am using Time.deltaTime on the applied gravity so thats
handled... but what if I skip frames 8, 9, 10?
at frame 11, my code says 'ok, timeToJumpApex has been passed, no more +y velocity` without applying the y velocity I should have gotten from those skipped frames

final nest
#

Does anyone know how to do a character selection thing in unity
I have 4 characters, third person, currently using cinemachine free look cam, but that can change if needed. In thinking character selection is like in a tavern, and upon hitting ready you'll spawn into the game

soft shard
# pure ore How can I get smooth gravity? My jumping and gravity seems too jittery to be smo...

That looks like it should provide you with control over gravity, and similar to this blog, although in this blog they are using a variable for gravity instead of using the global Physics.gravity value: https://gamedevbeginner.com/how-to-jump-in-unity-with-or-without-physics/#character_controller_jump - how are you confirming your jumping and gravity are jittery? Does the same effect happen in the scene view as well or just the game view? Does it also happen at a lower Application.targetFrameRate ? Does the jitter change if you try different values for your gravity and force?

Learn how to jump in Unity, how to control jump height, plus how to jump without using physics, in my in-depth beginner's guide.

soft shard
solar jungle
#

when inside the tavern, you'd choose which character to make active

final nest
#

I guess i'm just not understanding how to transfer the camera over to the real scene, let me take some screenshot hold on

dense estuary
#

I want to toggle a bool that's stored in a material, within a script. Currently I'm trying to do this:

public void CRTEffect()
{
    crtMaterial.SetFloat("IsEnabled", Settings.crtEffect ? 1 : 0);
    scanlineMaterial.SetFloat("IsEnabled", Settings.crtEffect ? 1 : 0);
}```But this code isn't doing anything
solar jungle
#

The way I do stuff like that is to give the character a tag called "Player" then you can find the object in the scene with that tag

#

my follow cam script just finds the player game object in start, so its guarenteed to always focus on the player.

For you, make sure the non-selected characters dont use the Player tag, only using that tag for the selection

soft shard
final nest
#

i need help setting up my scene for the main game, because right now after i hit ready, its just a camera that roates to follow my mouse

dense estuary
dense estuary
#

I added a debug just now, and the one with the "_" does seem to be correct, but it also just refuses to change the float.

crtMaterial.SetFloat("_IsEnabled", Settings.crtEffect ? 1 : 0);
Debug.Log("CRT Is Enabled = " + crtMaterial.GetFloat("_IsEnabled"));```
final nest
#

inside game manager in 2nd scene is a spawn point (which correlates to the teleport system when player walks into the cube on a raft)

what should the cinemachine target be? the spawn too?

dense estuary
#

I figured out the issue, for some reason the UI toggle isnt actually changing the crtEffect bool. I fixed it.

leaden ice
#

!code

tawny elkBOT
final nest
#
using UnityEngine;
using UnityEngine.SceneManagement;

public class CharacterSelection : MonoBehaviour
{
    public GameObject[] characters; 
    public int selectedCharacter = 0; 
    private void Start()
    {
       
        if (characters.Length > 0)
        {
            ActivateCharacter(selectedCharacter);
        }
    }

    public void NextCharacter()

        DeactivateCharacter(selectedCharacter);


        selectedCharacter = (selectedCharacter + 1) % characters.Length;

   
        ActivateCharacter(selectedCharacter);
    }

    public void PreviousCharacter()
    {
        
        DeactivateCharacter(selectedCharacter);

        selectedCharacter--;

      
        if (selectedCharacter < 0)
        {
            selectedCharacter += characters.Length;
        }

       
        ActivateCharacter(selectedCharacter);
    }

    public void OnReadyButtonClicked()
    {
        PlayerPrefs.SetInt("selectedCharacter", selectedCharacter);
        SceneManager.LoadScene("Private Island", LoadSceneMode.Single); 
    }

    private void ActivateCharacter(int index)
    {
        if (index >= 0 && index < characters.Length)
        {
            characters[index].SetActive(true);
        }
    }

    private void DeactivateCharacter(int index)
    {
        if (index >= 0 && index < characters.Length)
        {
            characters[index].SetActive(false);
        }
    }
}
restive canopy
#

is this a good time?

soft shard
restive canopy
#

I need a bit of help disabling a persistent canvas once loaded

soft shard
soft shard
restive canopy
#

not preventing

#

its just not working

#

so I tried to just disable the canvas itself

#

since its only purpose is to show a fade to black and fade from black

soft shard
#

What do you mean by "not working"? Is your code getting executed? Are you getting any errors or anything?

restive canopy
#

one second

#

vid 1 is with the runtime line of code disabled / commented out

#

vid 2 is with it active, which brings the fade from black animation, but at the cost prohibiting me from interacting with the cnavas holding the moveable objects

#

like the canvas itself is overriding the raycast

#

any suggestions?

#

NEVERMIND

#

I answered my own question!

edgy ether
#

is Vector2.Distance really expensive/slow?

#

i suggested it at one time as an option but was told it was pretty expensive to use

#

anyway, i was planning to use vector2.distance to adjust the size of an object based on how close to the center the said object was

#

since im not counting for Z, would it simply be faster to just get an Mathf.abs for subtracting comparing both objects x and y?

mellow sigil
#

If you need the distance between two Vector2s then Vector2.Distance is the fastest option

lean sail
edgy ether
#

ah

lean sail
#

for example, sorting based on distance could be solved with the sqrMagnitude if you aren't displaying the distances to the user

#

i find it funny it was ever said to be "pretty expensive" lol

edgy ether
#

thank you for clearing this up for me

warm valley
#

He's my brother dw

lean sail
warm valley
#

Just getting him to hurry up on toilet

#

šŸ’€

#

Not that bad yk

quartz folio
#

!mute 1279534456121720955 1d do not use this server for off topic or any other spam

tawny elkBOT
#

dynoSuccess dezert_monke was muted.

shadow wagon
#

one thing might be 10ns slower than another thing, which at face value sounds bad, and if you were writing highly optimised code its a saving that woudl matter, or if you were to call the function thousands of of times at once

#

you can afford to waste some nanoseconds, especially in an ideal case where youre only calling the function 60 times a second

#

anytime I worry about optimisation, is less focus on what methods are being called, and more on the actual way im calling/using something. its usually the general code itself thats slowing things down

#

that raises a good question, I've always heard people say "you shouldnt use X its very slow" but never have i seen anyone actually show actual benchmarks to prove their claim

lean sail
#

Honestly I can't tell what your point is here (or if you're asking something), theres a few things that you're stating which just doesnt make sense

shadow wagon
#

funny to see Instantiate listed above FindObjectOfType as its the latter that people always point out to say "dont use that its slow" but nobody thinks twice about having a for loop or coroutine frequently instantiate

leaden ice
#

FindObjectOfType does

lean sail
#

Well if you need to instantiate something, or many somethings, you need to use Instantiate

leaden ice
#

anyway as the link you posted says:

Please feel free to add/remove/make suggestions as*** I am only guessing here***:

shadow wagon
leaden ice
#

I agrree that people prematurely optimize

#

But that also doesn't mean to go out of your way to use slow techniques when it's not hard to do the better thing

shadow wagon
#

thats true, I suppose I overlooked that aspect

hexed pecan
#

Slowness of FindObjectsOfType scales with the amount of objects in your scene, instantiate does not. So it doesnt even make sense to compare them. And of course the speed of Instantiate depends on the complexity of the object

shadow wagon
#

I do find it strange to have never seen any actual benchmarks, it would be interesting to know for sure how things compare

lean sail
#

people have done benchmarks, but what exactly do you wish to compare? if you're comparing a .Find function to already having the reference (via like drag or drop, or telling the class what the instance is) then I have news for you which is gonna be faster

leaden ice
#

As mentioned things scale with the number of objects etc so benchmarks aren't necessarily useful or representative

restive canopy
#

alright

#

any suggestions how one might have an event trigger everytime a scene changes from one to another?

hexed pecan
#

Theres an event for that

shadow wagon
#

well, yeah, the benchmarks would need to be comparing like to like

restive canopy
#

oh ffs this script is doing my head in

lean sail
lean sail
restive canopy
#

can I not just grab the ChangedActiveScene method from SceneManagement and go about my day?

lean sail
#

most of that example code is just extra fluff showing what you can do with it

restive canopy
#

sadly Ive been too traumatized by Linux while studying C to get too cozy with C#

lean sail
restive canopy
#

works great!

#

thanks

toxic vault
#

don't know how else to share this. So apologies.

Play this itch.io demo - https://andtechstudios.itch.io/protracer
Switch a red/yellow bullet using mouse wheel
Switch to night mode using "2" on your keyboard
Switch to slow-motion using "Z" key.

That smoke tracer effect is what I am aiming for. And I can't find any assets on the store that do that. This one has terrible reviews.

I can't even find good tutorials about this except for tracers that look like laser shots from a star-wars game.

itch.io

Play in your browser

rigid island
#

looks like they only draw towards the end of the ray with smoke then lit up the hit with a glow, nothing fancy going on

#

I would check out the llamaacademy code on this subject, but instead of tracing the entire path limit it to when its close to the hitzone

toxic vault
#

The whole path of bullet is the smoke trail that gradually fades out

rigid island
restive canopy
#

last thing I wanna smooth out for this game, the players are going to be spawned in by instances

#

how then do I save the instance in a variable in a script?

rigid island
toxic vault
# rigid island then that makes it even easier

For someone who doesn't know how to even begin, can you help me get started please?

I have tried trail renderers, but those look like a the glowing bullet in that screenshot. Not the smokey trail

restive canopy
#

but one script spawns the instantiation

#

I want another script to grab that instatiation and store it in themselves

rigid island
rigid island
#
var instance = instantiate (etc..
OnInstantiatedObj?.Invoke(instance)```
#

then store them however you want, List or whatever

restive canopy
#

oh boy

#

So I know how to use var instance

#

but what is that second line

karmic stone
#

ive been so confused for 3 days on this, and im confusing myself even more every second. so i have like four different objects in this file. https://paste.ofcode.org/49E3wbGLg3vZdvHvTECZYh I have the parent tree, which has the attached script, and a rigidbody. I have the child of it, a cut area, that is being deformed in code, along with a log cutting object thats a quad with a boxcollider. Im having to do so many transforms and inverse transforms because i want everything to line up. I want to know if im understanding this right, the cutbox is in logcutting localspace for size and center. the cuttingmeshcollider and vertexes of its mesh are in the cut area local space, the raycasts have to happen in world space ie no parent. im getting so overwhelmed at the amount of converts im having to do and i dont really get how to make it simple. (my goal is to get the intersection of the logcutting boxcollider and cutarea, and from those 2 points, turn anything that direction is the same direction as the logcutting compared to the hitoutpoint to be on the intersection between the cutter and the cutarea, not just on the cutter.) is there any right way to accomplish this / do it simply?

pastel halo
#

is there a way to use 0-360 rotation in code?

there's an issue of euler vs quaternion. in code it seems to be 0-180 then 0-negative180 not 0-360.
having some difficulty figuring out how to solve this.

working on a lockpick system and a random range pie slice is generated (the valid area) but when it falls on angles where the flip occurs (180/-180) the system breaks or doesnt seem to know how to render that. ive been trying to debug draw it so i can see the angle but its confusing

karmic stone
heady iris
#

e.g. Mathf.MoveTowardsAngle

#

this will correctly move towards an angle measured in degrees

#

have a look at the documentation for Mathf -- there are others

pastel halo
#

Ok i'll check that out, that may help solve it. its a challenging thing to work out

rigid island
#

instead of doing

myScript1.Method(instance)```
#

cause now you need myScript1 inside the script nd any other classes you want to add to, it becomes a mess

dense estuary
#

I have a Radar script that detects when an object is within range of the player, and displays an icon at the position when a UI ray is at the same angle.
I am experiencing an issue where the icon isn't being displayed at the correct spot, the radar gameobject is 178 pixels to the right on the UI canvas, and the icon is acting like the radar is at the center of the canvas.
This is my code: https://hastebin.com/share/uququdumuj.java
How can I get the icons to display at the correct position?

restive canopy
#

OnInstantiatedObj?.Invoke(instance)

#

so just this?

#

like how do I format it?

#

WAIT

#

OH I SEE IT NOW

rigid island
#

its an event , for example you can do Action delegate

#

public event Action<MyType> OnInstantiatedObj

#
// inside another class that wants this object
myScriptThatSpawnsStuff.OnInstantiatedObj += Method;

void Method(MyType obj){
Debug.Log($"Hi, I'm {obj.name}");
}```
restive canopy
#

... oh god I think Im just fried

#

im seeing whats going on and I understand how it works

rigid island
#

just lookup "Observer Pattern Unity"

#

learn more

restive canopy
#

I just dont know how to applu that to my stuff

rigid island
#

wdym?

restive canopy
#

cause right now I got a script running to instatite a player object

rigid island
#

there is nothing complicated going on here. If you know how to pass objects into methods, its nothing different here.

restive canopy
#

no no no- its not that

#

one second

#

this isnt the way to do it, is it

#

cause what its basically grabbing at now is a blank game object

rigid island
#

huh ? what is this supposed to be

restive canopy
#

grabbing the instances and storing them in the variables

rigid island
#

this isnt a good way at all