#💻┃code-beginner

1 messages · Page 670 of 1

shut swallow
#

just removing it after the vfx has finished playing

frosty hound
#

If you're using a particle system, there is also a stop property on the component which you can set to destroy so it'll handle it itself once the system is complete.

shut swallow
#

I have a config like this:

#
                (
                    vfx_slash,
                    position: castCenter,
                    rotation: slashDirectionQuaternion

                );
                Destroy(vfx_slash, 8);
                SuspendSlashes();```
drowsy pewter
#

anyone from india

polar acorn
shut swallow
cosmic dagger
#

You destroy the prefab used to create the clone . . .

shut swallow
#

ahhh

#

so how should I fix it? slash = Instantiate(...) then Destroy(slash)?

cosmic dagger
viscid needle
#

can anyone tell me why my player is not available as a game object

shut swallow
#

now my problem is making the particle spawn properly relative to the player

shut swallow
rocky canyon
#

its only showing the gameobjects in the prefab

shut swallow
#

lol

#

mb

rocky canyon
#

no worries

viscid needle
rocky canyon
#

i meant to ping @viscid needle

willow iron
#

🤦‍♂️

rocky canyon
#

yea, u can manipulate cinemachine variables at runtime... (the way u do it varies tho) especially since the updated blue cinemachine

#

vs the red cinemachine

#

trial and error for me when i do

willow iron
rocky canyon
# viscid needle thank you soooo muchhhh!!!

keep in mind tho.. that prefabs can't really reference things within the scene unless they are already in teh scene..
say u instantiate a prefab... unless the thing thats referenced is inside the prefab... the reference will be broken..

#

u need to do things like that after the instantiation..

viscid needle
#

still does not work

rocky canyon
#

say an enemy needs to know bout the player..

  • spawn the enemy
  • reference the enemy..
  • tell it to assign the player (cuz now they both exist in the scene)
viscid needle
#

it works in the scene view but why not in prefab ?

polar acorn
willow iron
#

Dont know how code will fix my bullets being too fast for the engine to register, but its worth a shot i suppose

viscid needle
polar acorn
#

A prefab cannot refer to objects in scenes. You will need to set the variable after spawning this object in code

viscid needle
#

i made the player a prefab

#

i though that will help

shut swallow
#
        var castCameraLocation = playerCamera.transform.position;

        var castCenter = playerCamera.transform.TransformPoint(castCenterOffset);

        var vector3HalfExtents = new Vector3(1.25f, 1f, 1.25f);

        var slashDirection = castCenter - cameraTarget.position;
        var slashDirectionQuaternion = Quaternion.Euler(slashDirection);

        // spawning game object doesn't seem to align with direction
                GameObject slashvfxinstance = Instantiate
                (
                    vfx_slash, 
                    position: castCenter,
                    rotation: slashDirectionQuaternion

                );```
I'm trying to spawn the particle gameObject at the end of the white line (`Debug.DrawLine(cameraTarget.position, castCenter)`) with the direction of the particle pointing at the same direction, but somehow it doesn't work. Object is spawning in just fine, but for some reason I can't see the VFX except at certain positions at certain angles, did I instantiate incorrectly?
polar acorn
rocky canyon
#

theres 2 main ways of doing this

  • the thing u spawn has logic that "grabs" the player reference when it becomes into existence (in the scene)...
    something like this.. but be cautious of using Find methods...
#

the 2nd way is:

  • the spawner... (that spawns the prefab).. uses its opportunity to cache the object..
    and tell it to assign the player immediately after instantiating it
strong shoal
#

one question how would i take a gameobject rotation and rotate it at a slope angle???

rocky canyon
strong shoal
#

i have already tried it

crimson shadow
#

Hey guys! i have a problem that i dont know how to solve. I have script that handles all my inputs
onFoot.UseItem.performed += ctx => { if (!playerUI.isInventoryOpen) useSelectedItem.UseItemInHand(); };
like this, when i press lmb it calls function from another script

{
    ItemSO itemSO = inventoryManager.GetSelectedItem(false);//what item is selected
    if(itemSO == null)
    {
        Debug.Log("No item selected to use.");
        return;
    }
    ItemSO selectedItem = inventoryManager.GetSelectedItem(itemSO.isUsable);//this reduces item quantity on use
    if (selectedItem is IItemUse usableItem)
    {
        usableItem.UseItem();
    }
}```
and from scriptable object script it gets UseItem of that SO
```public void UseItem()
{
    // Implement the logic for using the seed item here
    Debug.Log("used");
}   ```
ill try to be as clear as i can, i need to check in UseItem for canPlant bool from my plantingmanager script, so if i can plant than i will use the item, but i cant get a reference in my SO to plantingmanager, if i will do it in my UseItemInHand, then every object even if its not a seed will have a check on canPlant which i dont want because i will have items other than seeds. i propably could just use old unput system and in every item use script i would wait for lmb input, but i wanna do it with new input system. I hope i was clear enough and at least someone can understand what im saying.
rocky canyon
#

theres something more going on in that code..

#

log ur hits..

#

it seems to be spamming between different hits.. (maybe when ur stuff rotates)...

#

u need to ignore the collider of the thing ur moving too ofc..

strong shoal
#

thats my code

rocky canyon
#

either with physics query logic things ( i forget what they're called) or a layermask

#

so its only hitting certain things

strong shoal
#

btw the ground is a terrain

rocky canyon
#

i think ur mixing up what normals are..
normals are perpendicular to the surface.. so for a surface thats flat.. (horizontal) the normal will be Vertical...

in ur case ur using slopeDir which is a forward vector along the slope plane... or "Parallel"

strong shoal
#

OH

#

I ACCIDENTALY

#

DID IT

#

SRY

rocky canyon
#

i think u can fix the code u have now with some type of normalization but im not totally sure

#

projections i kinda just fiddle with until i get to work. 😄

#

i do simple raycasts w/o the projectonplane.. so that bit was what threw me off a bit

strong shoal
#

i did it wrong

rocky canyon
#

closer tho

#

💪 lol

strong shoal
#

should it be hit.point???

#

wait

rocky canyon
#

hit.point is just the position has nothign to do with rotations /direction

strong shoal
#

i think i know now

#

IDKKK

polar acorn
# strong shoal idk

That wasn't a question it was a statement. I have no idea what "idk" is supposed to mean in response to this

strong shoal
strong shoal
#

im confused

#

what should be the direction aka vector

#

when im trying to rotate the game object around the slope angle

verbal dome
#

Setting transform.up to the hit normal should work, as spawn suggested

rocky canyon
strong shoal
#

I DID IT

verbal dome
#

Maybe your raycast is hitting the object itself?

strong shoal
#

like 20 secs ago

#

Vector3 slopeDir = Vector3.ProjectOnPlane(transform.up, hit.normal);

        transform.forward = slopeDir;
rocky canyon
#

once its rotated it should be just along the lines of rotating it along its local Y axis or w/e it is

rocky canyon
#

no more problems?

strong shoal
#

nope

#

its just floating

#

a little bit

#

like the character

#

but im gonna repair it

#

thx

rocky canyon
#

np, 🍀 good luck

strong shoal
#

the model is shaking

#

like left and right

#

all of the time

rocky canyon
#

probably a situation where ur moving it one method..and rotating it another method..
or vice versa.. some kind of sync/ rigidbody jitter perhaps
some movement logic in Update()
other logic in FixedUpdate() or relying on physics calculations(just speculations)

rapid laurel
#

Can anyone help with linking Firebase to Unity? I have an InitializeFirebase() method called in Awake(), but it never seems to finish initializing. When I try to save data to the Realtime Database, it fails because Firebase is still not ready. What could be the issue?

keen dew
#

Show code

rapid laurel
#

savePlayerStats is used on other script when my character dies

strong shoal
#

is there a way to fix that????

rocky canyon
#

for me i typically break up my objects into "container" objects

say the Outer wrapper (root container) is rotated by one script..
and then my Inner container is rotating inside that outter container..

strong shoal
#

so i am able to do it

rocky canyon
#

the base rotates (rotating the cannon with it).. but for the cannon rotation i rotate just teh cannon (inside the base)

keen dew
rocky canyon
#

keeping them seperate.. its ususally the only way i can get some of the things i want to work to work

#

plus rotations and quaternions break my brain most times

#

(its also how my player camera works) my player rotates his body left and right (camera just follows) and then the camera only rotates up and down.. but u combine those together.. and u get a full 360 range in all directions

rocky canyon
#

but thats all the info i really got.. you'll have to probably share ur entire script.. type out what u want to happen.. how u want it to happen and all that stuff..

#

and then someone thats a wizard with rotations will step in and can tell u the correct Rotation methods to use.. (as there seems to be dozens of em)

rapid laurel
#

the first line

keen dew
willow iron
#

what is the difference between an animatorstate and a childanimatorstate?

verbal dome
#

You won't need childanimatorstate unless you are doing editor scripting with the animator

zealous garden
#

I have a dodge roll animation setup for my player that uses root motion.
I have a few issues

  1. The roll animation does not seem to finish fully when pressing the roll key
  2. my camera does not seem to follow the player when dodge rolling ( can show relevent scripts for that)
  3. the player returns to the starting roll position when the dodge roll ends
#

When doing the dodge roll, it doesnt seem to be moving my character controller?

rocky canyon
#

root motion will only move the object the animator is attached to... (or that it has keyframes for)
if ur CC is on that Player gameobject.. yet the animator is on the KnightPlayer child gameobject i wouldnt expect the Player to move along with it at all..

zealous garden
#

The animator is on the player game object tho

#

which is why im confused

rocky canyon
zealous garden
#

Yes

rocky canyon
#

last i recall CC's dont like to be moved or animated.. thats why when u teleport one of them you have to disable the CC, then teleport it transform.position = teleportPosition; .. and then re-enable it

zealous garden
#

Character controllers dont like to be moved?

rocky canyon
#

but i can't say with any certainty how it reacts with RootMotion animations

rocky canyon
zealous garden
#

yes

#

thats all im using

#

Thats my code

#

The dodge functions are at the bottom

rocky canyon
#

thats an empty link

#

gotta save it and use the generated url

zealous garden
#

Mb

rocky canyon
#

what about the deltaPosition

#

i havent ever done root motion so idk.. u may have to force the CC to update to the rolll position

zealous garden
#

Hmm, but im using character controller.move, shouldnt that move it?

rocky canyon
#

ya, it'll move it however u tell it to move depending on whats inside the ()

#

but.. if ur animator is whats moving it.. idk

zealous garden
#

weird

zealous garden
rocky canyon
#

something about the avatar

zealous garden
#

Alright, so id switch the whole avatar to humanoid then right?

#

then the animations too

rocky canyon
#

im just looking thru threads and google searches.. cuz i dont do root motion ll

rocky canyon
zealous garden
#

ChatGPT making me lose my mind...

rocky canyon
#

you can also debug ur CC position over the duration of the rolll

#

see if it updates at all past the point u initatiate it

zealous garden
#

Okay, well, i can clearly see it doesnt move anyway, in the viewport

rocky canyon
#

ahh.. so it stops in its tracks

zealous garden
#

Yeah

rocky canyon
#

as soon as u trigger the anim

zealous garden
#

yeah exactly

#

But the mesh actually moves and does the animation

rocky canyon
#

okay.. well that seems like useful information

rocky canyon
zealous garden
#

Yes

rocky canyon
#

ahh okay.. now i got the full picture.. still no solution tho lol

#

are any of the clips mixed? like some being root motion and others not being root motion

#

ya, seems to me like ur gonna need to update the cc or the mesh. or whichever manually or theres something i dont know about with RootMotion. which is a very strong possibility

zealous garden
#

Yes, so all my other animations are non root motion, essentially only the dodge is root motion

#

And im enabling root motion as soon as the player rolls, then disabling it after

rocky canyon
#

ya, something about that peaks my interest..

zealous garden
#

its definately possible

#

because its been done before

rocky canyon
#

like if the last animation u were transitioning from is not.. root motion.. and then once the roll is complete it also transitions to a clip thats not root motion..

#

seems like that may matter.. but it also doesn't seem uncommon of something to do or try so im out of ideas

rocky canyon
zealous garden
#

very common in soulslike games

rocky canyon
#

well im not meaning the mechanic being common.. just the method ur replicating it

#

also seems like it would be common

zealous garden
#

I dont think its my code thats wrong though, did you see the animator?

rocky canyon
#

unless* the souls-like also uses root motion for the simple walk -> movement

#

u could always run a coroutine when u dashroll.. moving the player (x distance / second or w/e) towards the stopping location..

#

(do it manually)

zealous garden
#

Yeah I made a dodging in place animation just in case

#

So ill do that as a last resort

rocky canyon
#

that would be my only solution lol

zealous garden
#

but it wouldnt look as smooth to be honest

#

Yeah

rocky canyon
#

yea, it might

#

if u took the time to tune it well enough

zealous garden
#

I want to at least TRY fix this

rocky canyon
#

but ya,there has to be ^

#

heh ofc ofc

zealous garden
#

Maybe I should take this into the advanced code channel

willow iron
#

it can find the root gameobject fine, but is struggling to send a message for some reason

rocky canyon
#

so it snaps it back?

#

last guess.. im out of ideas 🍀

slender nymph
rocky canyon
#

i think the non-root to root to non-root + ur code is likely the issue

zealous garden
willow iron
slender nymph
zealous garden
#

with the animator.deltaPosition

willow iron
#

ah, forgot you could do both those things

rapid laurel
#

https://pastecode.io/s/rht78g61
Anyone can help again? my Firebase was not initializing because it starts before dependencies load, now i have used CehckAndFixDependenciesAsync and it gives me a null reference
reference = FirebaseDatabase.GetInstance(app).RootReference; <- NULL

untold elk
#

ok ty not pinging since its an old question

#

actually if my dontdestroyonload exists when im in scene and im then supposed to use onsceneloaded im assuming i make a function for the scene i open (read my question if yall havent seen it its above the reply i got that i just responded to above this comment) that registers it is opened with onsceneloaded but inside of the scene i have to go back to so it can ideally let me add a visual of like a check box for each one, and then after all four are done i can show the voting system ? should this script i make be inside the canvas for the ui i add or something else

rapid laurel
# rapid laurel https://pastecode.io/s/rht78g61 Anyone can help again? my Firebase was not initi...

I think i have found my error but doesnt know how to fix it...
if I start firebase without the FirebaseApp.CheckAndFixDependenciesAsync method it starts fine but without the dependencies loaded then it does not let me upload data to the RealtimeDatabase, but if I use it and wait for them to load the method never finishes, so I understand that it does not find them or it is not loading them for some reason.
Has it happened to anyone?

untold elk
#

also in 3d worlds with unity toggles how do i move them as i do not get arrows like buttons do in unity

timid salmon
#

heyy guys! Just Trying to figure out wether ot not u can check how much force an object has after u apply it in a script

polar acorn
#

Force causes changes in velocity

#

but there's no way to go back from velocity to the amount of force used and when it was applied

timid salmon
#

can you check if the velocity meets a certain speed in a script to then do something?

naive pawn
#

why not?

#

it's a variable like any other

timid salmon
#

I need to check if the velocity is higer that 10 to rotate my object

#

How Would i acheive that in a scriptatwhatcost

polar acorn
#

But velocity isn't a number, it's a vector

#

It has direction

timid salmon
#

Ohh

#

So How Would I Script That..

naive pawn
#

depends on what you actually want

timid salmon
#

something like

naive pawn
#

x velocity only? y velocity only? z velocity only? overall horizontal velocity? overall velocity?

timid salmon
#

if ( rb.velocity =< 10)

naive pawn
#

yeah that doesn't make sense - again, velocity is a vector

polar acorn
#

It's got X, Y, and Z components

#

You would need to get a numeric property of it like .x or .magnitude or something

#

Whichever one you want

timid salmon
#

so would it be something like if ( rb.velocity.x ?

naive pawn
#

you'd have to actually check it against something

polar acorn
#

Do you want to check the X velocity?

#

What value do you want to check?

timid salmon
#

Yeah!

polar acorn
# timid salmon Yeah!

If you want to check if the X velocity is greater than 10, that'd be a good way to do it

timid salmon
#

Great

#

Srry For pesturing but how would i do that..

naive pawn
#

sounds like you're missing some c# fundamentals

#

see the pinned resources

timid salmon
rotund forum
#

I want to give a list of "goals" to the enemies in my game (the goals determine how the enemy state machine's states function in order to reach said goal), but I'm coming across an issue where Unity does not want to serialize abstract classes. Seems like inheritance is not something you can do if you want to serialize a class.

I did start using scriptable objects and now I can have an abstract base class that the other goals inherit from (while the base class inherits from scriptable object), but there's another issue. I wanted to expose some variables in the editor in my list, but since I'm working with scriptable objects now all my goals are references to assets in my project; I can't change any variables (like patrol range or how much health they'll retreat at) in the GoalManager class's list, I have to do it on the scriptable object meaning I need slight variations in similarly functioning scriptable object "goals" if I want different enemies to, for example, patrol with slightly different parameters.

Am I making this too convoluted or is there a better way to do this? Or are scriptable objects the best option here?

Appreciate any help or feedback. Thank you.

polar acorn
naive pawn
#

it's not the inheritance that's the issue, it's the abstract being an issue

timid salmon
#

i undersand what the less than or more than keys work yet im struggling to find wha it would actually look like in a scriptUnityChanSalute

timid salmon
naive pawn
rocky canyon
#
if(condition)
{
// execute
}``` where condition would be something like `rb.velocity.x > 10` or `rb.velocity.x > someVariable`
polar acorn
timid salmon
rotund forum
slender nymph
polar acorn
# timid salmon
  1. you can't set an individual component of a property on the same line you get it
  2. Rotation is a quaternion and you very very should not be editing an individual component of it
timid salmon
naive pawn
#

yeah, what about it?

slender nymph
timid salmon
#

i feel like a 4 dimentional aspects of unity would be a lil to hard for me to understand at the point im at along with my age

naive pawn
#

this isn't a unity 4d thing, this is just a math thing - quaternions are necessary to accurately represent and manipulate on 3d rotations

#

don't worry about understanding quaternions, just treat them as a black box. don't modify them, don't try to interpret their internal values unless you really want to get deep into the math

timid salmon
#

Okay, Thanks

polar acorn
#

If you're ever modifying an individual component of a quaternion, don't

naive pawn
#

also iirc rotation quaternions are normalized, so modifying a component would directly make it invalid

timid salmon
#

ill try adding some of the stuff you guys have suggested and see if it helps me with my problem!

plucky kernel
#

I cannot figure out how to change the "front direction" of a Unity prefab and get it to work with my script. I have this "Arrow" prefab (a fork. This is a college project and we're supposed to use free assets) and put it as a child in the Vehicle object so that it's automatically in a fixed position over the car. My script works when I pass in the Arrow child object and it always faces the nearest Waypoint, except the "front" of the object is not the prongs of the fork (or whatever they're called). I asked about this problem before and the answer I received was the same as the internet. So, I put the fork in an empty GameObject and rotated what I wanted to be the "front" of the fork to match the Z axis of the GameObject. I put the GO as a child of the Vehicle and then attached it to my script instead of attaching the fork itself like I did previously. Now the fork doesn't rotate and instead moves all over the place whenever the car moves. I checked the Inspector and saw that the GameObject itself is rotating, while its child, the fork, doesn't rotate at all. The script I attached is just the Arrow rotation part. It's apart of the WaypointSpawnManager, which is a bad idea, but the project just needs to work and I need to submit it already as well. So, ignore that part, since the Arrow just needs information from the Waypoints in the list and is unaffected by the spawning script I didn't include https://hastebin.com/share/ruqolujuko.java
The second image shows the rotation of the fork. The Move Gizmos are the empty GameObject, not the fork

polar acorn
plucky kernel
#

I'm not sure, but both objects' coordinates are different from each other

#

neither are at 0,0,0

polar acorn
#

the values showed there are local space

#

is the fork at position 0,0,0?

plucky kernel
#

oh ok, then no

#

I see that it says it's around 18, 27, -60

#

how should I get it to 0,0,0 relative to the EmptyGOArrow?

#

I'm still very confused with how Unity works

polar acorn
plucky kernel
#

oh

polar acorn
#

The inspector shows the object's position relative to its parent

plucky kernel
#

that's it...oops

#

ohhhhhhhhhhhh

polar acorn
#

Putting it at 0,0,0 means it's at the parent's location

#

So when you rotate the parent, it'll spin this object about its center

untold elk
#

!code

eternal falconBOT
untold elk
#

hi i know i was told to us OnSceneLoaded in order to verify that a scene was opened but do i do that in my script that allows me to open the scene and also how on earth does this apply in my main script that verified if each scene loaded loaded

plucky kernel
polar acorn
# untold elk hi i know i was told to us OnSceneLoaded in order to verify that a scene was ope...

OnSceneLoaded is how you'd register a function to run whenever any scene is loaded. If you just want to know that every scene was loaded, you could just make this script a DDOL singleton and set a boolean flag whenever you change scenes. Then you can do something when all of them have been visited.
https://gamedevbeginner.com/singletons-in-unity-the-right-way/

Learn the pros & cons of using singletons in Unity, and decide for yourself if they can help you to develop your game more easily.

timid salmon
#

i cant figure out how to do what you've guys told me so i just given up

#

i still thank you guys for trying but its just too frustrating

untold elk
untold elk
#

ill try that out first see what happens and report back

untold elk
#

wait so if i put a boolean in my inputhandler script section that opens my scenes i do inside the script checking singletons

void Start()

if(OnsceneLoaded.booleenname)
{

//run the singleton?


}
``` or is this wrong cus it also would mean the singleton loads per scene and since its a singleton it destroys itself if it runs more than once so then is the boolean made inside the singleton and i run the singleton in the script that loads my scenes?
#

i feel like maybe im supposed to run the boolean and define it by the singleton somehow like boolean only true when all four scenes are opened? confused i am

#

also i need to define my singleton how so?

rich adder
#

damm we still on this scene counting thing lol

rich adder
untold elk
#

i read that but just realized theres more in the site lmao

#

his tutorial gave an example of setting a float variable to a singleton but i want to define the singleton so i can have it not show an error

rich adder
rich adder
untold elk
#

it says the name of my singleton can not be found

rich adder
untold elk
polar acorn
rich adder
untold elk
#

that is supposed to be the name of the singleton is singleton always supposed to be called Singleton?

polar acorn
rich adder
polar acorn
#

Right now, it's a variable of type ScenesAccessed, do you have a script named ScenesAccessed?

rich adder
#

instance = this would error because you're trying to assign EnableVote as ScenesAccessed, whatever that is..

untold elk
polar acorn
untold elk
rich adder
#

so ScenesAccessed is some made up class?

polar acorn
rich adder
#

the whole point is so you can access whatever is in EnableVote(methods, public fields etc.) through instance since its static and easy to access from other scripts

untold elk
untold elk
rich adder
#

because its always going to hit that specific EnableVote through instance

#

the singleton pattern just makes it so its only 1 that exists, is just there so you can easily access it from any other scripts static makes it belong to class itself , hence no need for a field reference / link through inspector

untold elk
#

and ofc runs the method im using like foo

rich adder
polar acorn
#

A "Singleton" is just a name given to the sort of pattern of having a static variable that holds a single instance of a class

#

Since there is always exactly one instance of it ever, you know you can always access it

rich adder
#

would be easier to understand if you learned plain c# first lol

#

knowing what instances are etc.

untold elk
#

ohh ok but then when u mentioned the boolean digiholic what would i actually use that for in combo with the singleton

#

is that inside it?

polar acorn
untold elk
polar acorn
#

then you could set and check that variable in some other script

#

And if this object is a DontDestroyOnLoad it'll keep its variables across multiple scenes

rich adder
#

Unity kinda forces you to catapult into something like this because yeah between scenes is the easiest option believe it or not

#

since a DontDestroyOnLoad gameobject will be in a scene literally called DontDestroyOnLoad that does not get unloaded until you end the game/simulation

#

if you're making a bool in EnableVote just make sure its public, anything you must access through the singletons instance must be public (regardless of a singleton, this is a common thing to do if you want to access anything between scripts)

rich adder
# untold elk

also do configure your VSCode. Its part of the requirement here and plus it will benefit your coding..
You should be seeing suggestions like this and red underlines especially the error you currently had should've been underlined red..

untold elk
#

it says i need .dot and i already have unity installed on vs and i think i need nuget or sum likethat just notified me to be fixed as well

rich adder
untold elk
rich adder
cosmic charm
#

My player gets stuck between tiles for some reason, and I don't know why, even my skeleton, I used capsule colidor and it didn't fix it

wintry quarry
cosmic charm
#

OMG

#

I LOVE YOU

undone depot
#

how can i update variables set in another script? the readyToAttack variable here is from a different script

ivory bobcat
#

For example: cs public Player player; ... player.readyToAttack = false;

undone depot
#

so Player here would be the script im wanting to access?

undone depot
ivory bobcat
#
[SerializeField] private Player player;```would suffice if references can be made in the hierarchy-scene outside of runtime.
untold elk
#

with my singleton function set up how do i fix it so the red line under EnableVote.Instance.Example; goes away


            case "TedBearClick":
                Debug.Log("Loading Slide...");
                SceneManager.LoadScene("TR");
                EnableVote.Instance.Example;
                break;

wintry quarry
ivory bobcat
untold elk
#

this is the error im looking up issue debug rn

wintry quarry
#

you have a line of code there that does nothing

#

so it's not valid

untold elk
#

ohh ok

wintry quarry
#

Imagine you have a line of code that just says "Apple"

#

well.. why did you write that? What do you want to do with the Apple?

#

it needs to be either an assignment (using =), a method call (MyMethod();), an increment or decrement (++ or --) or a call to some classes' constructor (new xxx())

untold elk
#

my question is though if that is what defines a singleton occured 'Instance' and is what is undefined but is used as the way to define a singleton and should call a singleton in my code why is it that i need to define instance?

#

like it doesnt error in singleton code section and i thought u use instance to refer to the singleton

#

mg nvm i fixed it

undone depot
ivory bobcat
#

You likely haven't assigned anything to your player variable/field yet.

ivory bobcat
undone depot
ivory bobcat
# undone depot

So, you've got to assign sword an instance reference before using sword

undone depot
#

alright so that's what the error said but im not really sure how to do that

rich adder
brave robin
#

And then do what nav said

rich adder
undone depot
#

oh alright

#

thanks

sour fulcrum
#

Just vibe checking because googles are suprisingly not providing a great answer,

Bounds contain checking is like dirt cheap right?

teal viper
sour fulcrum
#

Fair, I think it's the best option for what I'm doing but just curious if it's comparable to something like distance checking or raycasting cost wise.

With some simple caching i'd be doing 1 bounds check per update on say a dozen objects

On certain frames it would be like 20-50ish bounds check on one of those previously dozen objects

I can probably find more ways to avoid certain checks but if it's cheap enough it's probably fine. I'd profile it but for reasons i can't go into im not in an environment where that's as easy

teal viper
#

Though, again, if we're talking 50 bounds checks vs 1 raycast, it's more nuanced

#

A raycast could be faster depending on the context

zenith cypress
sour fulcrum
#

ideally i'd do this sort of things via triggers and such but unfortunately not in the position to do so

ivory bobcat
wintry quarry
#

pretty sure the first part of raycasts are a broadphase cast against the AABBs

#

so bounds checking in a sense is sort of a lower bound on the performance of a raycast

lilac cape
#

Hey all, I made a new beginner script that uses the new input system and I'm wondering if I can improve my code organization anywhere. Currently, the script just has basic actions like Move, Jump, and Look for now. Happy to take any criticism as I want to write code that doesn't make other devs yank their eyes out...
https://gist.github.com/NullSimLabs/a054fc38f3780c23c485e46f823cdd24

teal viper
wintry quarry
teal viper
#

Indeed, but it might be way less checks than they would do manually

wintry quarry
#

oh certainly it's not checking every AABB

tiny musk
#

hello everyone i had a problem my friend export the scene and send me to import when i import that scene that will show all line error like show all unity methord underline in redcolor but that will run correctly but this is show in visual studio community what i do but other project didnot show that what is the problem i want to know please anyone tell about this , i already take actions 1) uninstall and reinstall visual studio community , 2) regenerate file , 3) uninstall and reinstall the vs community pakage in unity . any other thing i want to change please anyone tell about this

brave robin
#

Looks like VS isn't properly setup to tie into Unity, because it doesn't recognize any of Unity's classes

tiny musk
#

ohh ok bro how to slove that

#

do you know

brave robin
#

!ide

eternal falconBOT
brave robin
#

Pretty sure the info is in one of those links, but it's been a while since I've done it myself

tiny musk
#

ok bro thanks for your help i will try that

spare mountain
#

using xyz

#

at the top of your file

tiny musk
#

what bro i did understand

spare mountain
tiny musk
#

ok wait minute please i will send that

#

@spare mountain here bro

spare mountain
tiny musk
#

unity methord underlined in red color in visual studio community that is the error

wintry quarry
#

you're supposed to actually read the errors

#

mouse over one to read it

#

also double check if the errors are also in Unity's console and not just in VS.

spare mountain
tiny musk
#

@wintry quarry
ok bro but i when i type the code in visual studio community that is suggest the code and when ever i use unity methord that is look like methords it only looks like text

spare mountain
wintry quarry
tiny musk
#

hello everyone i had a problem my friend export the scene and send me to import when i import that scene that will show all line error like show all unity methord underline in redcolor but that will run correctly but this is show in visual studio community what i do but other project didnot show that what is the problem i want to know please anyone tell about this , i already take actions 1) uninstall and reinstall visual studio community , 2) regenerate file , 3) uninstall and reinstall the vs community pakage in unity . any other thing i want to change please anyone tell about this

wintry quarry
#

Are you a bot?

tiny musk
ivory bobcat
#

Might be some language barrier tbf UnityChanThink

wintry quarry
spare mountain
#

@tiny musk what language do you speak

tiny musk
#

tamil

spare mountain
# tiny musk tamil

அது என்ன பிழைன்னு உனக்குச் சொல்லுது?

tiny musk
#

when i use unity methords like Transform and Gameobject this kind of methord there this red underline show that the issue i am facing

wintry quarry
tiny musk
#

ok

spare mountain
#

whoof

tiny musk
#

system objects is not defined or imported bro

wintry quarry
#

definitely some kind of bad VS install or something

spare mountain
wintry quarry
#

Those steps mentioned above are absolutely what I would have recommended to fix it though

#

So if they haven't fixed it, idk really.

tiny musk
tiny musk
wintry quarry
spare mountain
tiny musk
#

VS Community 2022 bro

spare mountain
#

@tiny musk try reinstalling the unity plugin too

tiny musk
spare mountain
#

yay

toxic cove
#

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class Get : MonoBehaviour
{
public GameObject Gun;

// Start is called before the first frame update
void Start()
{
    Gun.SetActive(false);
}

// Update is called once per frame
void Update()
{

}

private void OnTriggerStay(Collider other)
{
    if (other.CompareTag("Player"))
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            this.gameObject.SetActive(false);
            Gun.SetActive(true);
        }
    }
}

}
Whenever I click E when my camera is pointed at the object it still wont wont Activate the one that is suppose to activate

wintry quarry
wintry quarry
#

What is the intention of this script? Which object is it attached to? What's it supposed to do?

#

What are you trying to accomplish

toxic cove
wintry quarry
#

OnTriggerStay is for physics objects that are touching each other when one has a trigger collider

#

nothing to do with cameras

toxic cove
wintry quarry
#

What you're describing sounds like something you would do with a raycast

toxic cove
#

or something

wintry quarry
#

raycast is from wherever the hell you want to wherever the hell you want

#

You can write code that does anything.

toxic cove
#

and I don't know how to actually make it do something in a script.

wintry quarry
#

It's not expected that you should when you're a beginner

#

that's why you learn

toxic cove
#

Thank you though!

wintry quarry
#

you're at the very beginning of your journey

toxic cove
wintry quarry
#

find a better tutorial 😛

toxic cove
wintry quarry
#

Find one that uses a raycast

feral glen
#

i am trying to make my character (2d) not slide down any slopes in my scene, i am using a character controller i got from online
i tried making some changes to it i.e. making my character velocity 0 when standing straight which did nothing
so what should i do now?

#

this is the part

versed light
#

when i add a navmesh surface why does this weird image appear at the object position

viscid needle
#

how to send you guys my code?

wintry quarry
eternal falconBOT
wintry quarry
viscid needle
#

i tried to debug.log to check if functions are happening

wintry quarry
#

so... are they?

viscid needle
#

but the takedammage function is not bieng called i think

wintry quarry
#

What about OnTriggerStay2D

#

let's start there

#

also why do you "think"? If you used Debug.Log you should know for sure if it is or isn't.

viscid needle
#

i would know if the function was bieng called

wintry quarry
#

yes

#

that's the point of the logs

viscid needle
wintry quarry
viscid needle
#

just that

wintry quarry
#
  • DO you see errors?
  • Do you see "Player taking damage"?
viscid needle
#

no

wintry quarry
#

ok then clearly there is an issue with your conditions in OnTriggerEnter2D

viscid needle
wintry quarry
#

if (other.CompareTag("Player") && Time.time >= nextAttackTime)

#

So keep debugging

#

you need to now log these things

#

As well as this: if (playerHealth != null)

viscid needle
#

i did not understand

wintry quarry
#

Add more logs

#

print out the values of those variables and expressions

#

then you will find out why the if statement is failing to enter and call your takeDamage function

viscid needle
#

ok ig thnks

sharp abyss
#

When my colliders are trigger, no problem but when isnt,my player just flies everywhere. I tried to exclude all layers for collision but it still did the same thing when it isnt trigger.What can I try?

visual oasis
#

is this an acceptable way to only invoke a C# event once without having to use flags:

public void Update() {
   if (player.health <= 0) {
      onPlayerDie?.Invoke();
      onPlayerDie = null;
   }
}
#

Alternatively with a wrapper like TriggerEventOnce(onPlayerDie);

teal viper
north skiff
burnt vapor
#

Use a boolean to check if it invoked, don't unassign the variable

north skiff
#

i.e. booleans

burnt vapor
#

Why would you do this? If the point is making sure a player doesn't emit its death multiple times, then keep a state represented by an enum to specify if a player is alive or death

#

You are practically omitting the issue by doing this, and it will introduce unnecessary complexity

#

Better to just implement the missing feature

teal viper
#

I'd invoke the event wherever the health is reduced, instead of update.

north skiff
#

i would argue it's actually a clean solution as long as you are not "expecting" to see flags in your code, it might be harder if you are collaborating with experienced Unity devs used to flags

teal viper
#

And have a flag there as well(in case objects bellow 0 health can be damaged)

north skiff
#

you are effectively using flags while omitting an extra variable

burnt vapor
#

This is anything but clean, because now your code unexpectetly removes events from the code just because one instance doesn't want it to emit multiple times.

#

That specific instance should better handle its use case, being that the player should only actually die once.

#

Only specific instances should subscribe/unsubscribe itself, it is not up to the invoking code to do this

north skiff
#

so you are saying that the event should be executed even when dead?

#

but then handle the "already-dead"-case in the event code?

#

that has to be more inefficient

burnt vapor
#

Which by itself would be more efficient

sour fulcrum
#

imo for it to even remotely clean it would have to be some class wrapping around the event, like a SingleFireEvent. I don't ever expect event refs to be null

burnt vapor
#

Player reaches 0 health, you set the state to dead, you run the event.

north skiff
#

right, i agree

burnt vapor
#

Next time the method is called, you see the player's state is dead, you end the method with no logic being invoked

burnt vapor
#

Just add a state lol

north skiff
#

i guess i just assumed that there could be weird glitches or bugs where the player may die more than once and then this solution could be a decent catch for it

#

but of course removing the possibility of those bugs in the first place is ofc the cleaner solution

burnt vapor
#

You can always refactor extra variables later. You can't refactor an event being unset when everything now relies on that

burnt vapor
#

I'd argue it's even better because you can implement a way for it to be an atomic operation

north skiff
#

sure, i agree

viscid needle
#

!code

eternal falconBOT
viscid needle
keen dew
teal viper
burnt vapor
#

Seems odd, maybe just a school exercise

viscid needle
#

only the enemy is able to detect when it touches the player @teal viper

#

nothing else

viscid needle
keen dew
#

Do you know what if (other.CompareTag("Player") ) does?

viscid needle
#

.... oh

#

thank you so muchhhh

#

i am stuck with this bug since morning

teal viper
burnt vapor
# viscid needle i am stuck with this bug since morning

For future reference, the debug log Damaging player! you added would not show. This would have meant that the if statement failed, suggesting the tag is incorrect. Next time you can log the current tag being returned to quickly find out it is wrong

viscid needle
visual oasis
visual oasis
#

more intuitive clarity

#

but then

burnt vapor
#

Also very reusable. You definitely need to know a player's state later on anyway

#

Like movement, you can't move when dead. Stuff like that

visual oasis
#

Should I use a boolean? Or should I use an enum with two states? Or maybe a full-on state system with other things too?

visual oasis
burnt vapor
#

I generally vouch for an enum even if it's just two states, for clarity. Who knows you might also want to extend the state to allow for a spectating state, for example

burnt vapor
#

Otherwise you have a lot of instances where you might have to lock or unlock the controls, risking a case where you forget it

visual oasis
#

so would this be something like

public enum LivingState {
  Alive,
  Dead,
}
burnt vapor
#

Pretty much

visual oasis
#

fair enough

#

and it's an enum so not exactly taking up any more memory

burnt vapor
#

You can also make a property IsAlive that checks against this if you don't want to explicitly check the num constantly

#

Though generally I'd just check the enum. Otherwise you might wonder in a month what IsAlive actually does as the logic is moved elsewhere

visual oasis
#

like

public bool IsAlive {
  get => livingState == LivingState.Alive;
}
#

is that a property

burnt vapor
#

Close

public bool IsAlive => livingState == LivingState.Alive;
#

This is the same thing. You don't need to explicitly specify the accessor if you just use the getter

#

Both work

visual oasis
#

and this prevents setting right

naive pawn
burnt vapor
#

Yes, you can only mutate livingState when you have access to it

naive pawn
visual oasis
#

ok, something that's actually been on my mind for a while:
is it at all common practice to also have an IsDead as opposed to checking !IsAlive?

burnt vapor
# visual oasis is that a property

Yes and as such you can specify how it's used. The individual get and set accessors can also not be added, or you can for example make them private (private set;)

burnt vapor
#

You know it's all extra code and generally complications. That's why I suggest you just check the enum unless there ar emultiple things to check

#

Like not just the enum here, but also another variable. Then I would put it in a property.

visual oasis
#

ah, i see

#

and in that case using a property could be good future-proofing too i suppose

burnt vapor
#

Also because state == LivingState.Alive is very informative and you can't really make a mistake here

burnt vapor
#

But even then I would be careful, maybe an instance that uses this property doesn't want to check another variable and strictly check the state instead. This would end up causing undefined behaviour

naive pawn
#

@visual oasis why not handle it wherever you take damage? is health public or something?

burnt vapor
#

So that's why I would still suggest to just set the variable and check that instead. ONLY use a property if you want to change the accessibillity

#

_livingState would be private, but you'd have a public property to access it (but not set it)

naive pawn
#

is the health bar retrieving the health, rather than the player controller setting the health?

#

anyways that aside - how do you deal damage?

visual oasis
#

the health bar retrieves the health, yes

#

and...

#

my game's a 1D (forward and backward movement only) tower defence

#

so when an entity attacks, it triggers a DealDamage() function in the GameplayManager instance which then checks what's in range and deals damage to entities that are indeed in range

#

or if it's single-hit attacks like arrows, it checks what's closest

#

This doesn't use events at all, and I'll be looking at how I can refactor it to use them instead

naive pawn
#

well it doesn't have to necessarily use events

visual oasis
#
// class GameplayManager
    public void DealDamage(string entityId) {
        GameplayEntity entity = entities[entityId];
        foreach (GameplayEntity enemy in entities.Values) {
            if (enemy == null || enemy.allegiance == entity.allegiance || enemy.currentState == GameplayEntity.State.Die)
                continue;

            if (entity.IsInMeleeRange(enemy.xPos + 0.2f * enemy.direction))
                entity.MeleeHit(enemy);
        }
    }
naive pawn
#

my point is, if you put dealing damage and the death trigger together, it becomes much easier

visual oasis
#

yeah, I do now plan on doing that

naive pawn
#

you aren't actually dealing damage here though...?

#

where are you actually dealing damage? as in, updating the health variable

visual oasis
#

entity.MeleeHit(enemy)

#
    public override void MeleeHit(GameplayEntity target, float damage) {
        target.Damage(damage);
        meleeWeapon.data.PlayHit();
    }
naive pawn
#

that's still not it

visual oasis
#
    public virtual void Damage(float damage) {
        health -= damage;
    }
naive pawn
#

there we go

#

so each entity does manage its own health

visual oasis
#

yes

naive pawn
#

so you could just..

    public virtual void Damage(float damage) {
+       if (health <= 0) return;
        health -= damage;
+       if (health <= 0) onPlayerDie?.Invoke();
    }
#

instead of doing it in Update

visual oasis
#

yeah, i'll do that

naive pawn
#

this was the first thing suggested (by dlich) lmao

visual oasis
#

i'm also wondering how i can optimise the enemies-in-range checking system, but that's a question for another time

naive pawn
#

probably overlapshere or smth

visual oasis
#

like, a physical sphere?

#

it's my first time using a 3D game engine, so all my collisions are done with pure math and code rn

visual oasis
#

no collision boxes

#

the physics engine

#

is it faster though

#

in my mind it'd be slower because it's a whole engine vs a simple calculation in code

naive pawn
#

probably not. it's not gonna be slow enough to matter though

#

they're tried and tested systems

visual oasis
#

but is it faster thinking

naive pawn
#

probably not

#

i mean, i guess it depends on the context/scale

#

your thing scales by how many enemies there are overall

#

using the physics system, i'd expect it to ignore very far things, but im not sure how it really works internally.
i'd expect some kind of optimization there, at least

#

but there probably is some overhead for the system as a whole, yeah

#

but we're talking on the scale of microseconds here, it's not gonna matter

visual oasis
#

hmm hmm

#

that means i need to add a collider to all my objects though, right?

#

the entities

naive pawn
#

yeah

visual oasis
#

kk

#

i'll def try it out then

naive pawn
#

if you had an entity prefab you would just add it to that prefab

visual oasis
#

well, i have a prefab for each entity

naive pawn
#

..each entity type?

#

or each actual entity?

visual oasis
#

individual

naive pawn
#

that's not right

#

...why?

visual oasis
#

oh i see what you mean

#

err entity type yeah

#

so farmers vs sword warriors vs spear warriors etc.

#

each with their own different meshes and whatnot

naive pawn
#

yeah ok that makes sense

#

are they just individual prefabs completely, or are they variants (with a common base)?

visual oasis
#

completely individual

odd swift
#

is anyone able to help me i got an assignment due tomorrow and i just need to figure out this one bit of code for then i can show the teacher tomrrow? anyone?

naive pawn
#

!ask

eternal falconBOT
naive pawn
#

especially that last point - noone can help if we don't know what you need help with

odd swift
#

srry mb first time asking for help lmao

#

gimme a sec

visual oasis
#

what if i add the collider in code

naive pawn
#

you wouldn't be able to check if they line up

#

wait you said meshes right?

visual oasis
#

yuh

naive pawn
#

wouldn't you be able to just multiselect all the prefabs and add a meshcollider to all of them at once?

#

or i guess capsulecollider if you want a simpler view

strong wren
#

Adding components at runtime will likely be slower. I wouldn't bother with the physics engine just for distance checking if you can manage it yourself.

naive pawn
#

not sure about any possible caveats with a meshcollider vs a primitive collider - i usually work in 2d

visual oasis
#

well, the game is effectively 2D

#

1D really

#

with 3D graphics

odd swift
#

So my goal is to call a function once all the dialogue is completed that will then display a button for the player to press, the spot to which the dialogue is finished is in the first image and then i want it to enable the button

#

srry if that dosent make sense just tell me

naive pawn
naive pawn
odd swift
burnt vapor
eternal falconBOT
naive pawn
#

to do what, call a function?

naive pawn
#

ok click the button labelled vscode

odd swift
naive pawn
#

it's not configured, follow the steps provided there

odd swift
# naive pawn to do what, call a function?

im not sure myself, im just learning all this and my teacher dosent even know anything about it its stupid, but i want after the else statment that it enables the button

odd swift
naive pawn
odd swift
burnt vapor
# odd swift i already have vs code setup tho

Yes, but judging from the screenshot it is not fully configured. Generally I do advice you use Jetbrains or Visual Studio as the setup is much easier there, but VSCode also works.

odd swift
naive pawn
#

seems to have not worked. have you been presented with the "install .net sdk" window?

odd swift
burnt vapor
odd swift
#

thank you tho

naive pawn
#

check the output window in vscode

#

it should be beside the terminal - if you don't have that open, i think the default keybind is ctrl+`

odd swift
#

thats what my output looks like

#

hold on i do get errors when i open the app

#

is it anything to do with this

naive pawn
#

yeah you haven't installed the .net sdk

odd swift
#

oooh

#

i see

#

leme press get the sdk

#

alright its installed now

naive pawn
#

now reload the window and see if it loads colors now

odd swift
#

better?

naive pawn
#

no, MonoBehaviour should be green

#

what does the output window say

odd swift
#

im on mac if that makes a difference

naive pawn
#

it shouldn't

#

on the right where it says .NET Install Tool, try changing that to c#

odd swift
#

kk

#

here we go

naive pawn
#

try going to unity > preferences > external tools > regenerate project files

#

and make sure the external script editor is set to vscode

odd swift
#

alright

#

this is what it has always looked like

untold elk
#

i cant find the answers to my questions but just finished my first game and singleton and bool ty everyone for helping 🙂

odd swift
odd swift
naive pawn
#

yeah there you go

naive pawn
odd swift
#

i apperciate your patience btw

#

my spelling 💀

naive pawn
#

fields that are public or marked [SerializeField] will be shown in the inspector
you can use a field typed GameObject to get the button so you can call SetActive on it

#

these are pretty basic unity concepts so...

odd swift
shut swallow
#

is there any way to call component of the prefab? I'm trying to control play state of the particle graph

naive pawn
untold elk
# cosmic dagger What question?

it was from last night in regards to singletons and booleans i really just wanted anyone who helped to see that so they know it resolved itself

shut swallow
#

(I passed argument GameObject instance into SuspendSlashes)

odd swift
naive pawn
shut swallow
naive pawn
#

you can pass types other than GameObject to Instantiate, and you'll get the same type back as a reference to that component on the newly created gameobject

#

so you could type vfx_slash and slashvfxinstance as VisualEffect instead

#

(and then use slashvfxinstance.gameObject in the Destroy call)

naive pawn
steel wagon
#

hi im pretty new to programming and tried to follow a tut for my assignment. and i cant seem to drag the script to the inspector. i dont get what class is it refering to because i already checked and it is already the same as how the tut provided

shut swallow
naive pawn
#

i'm happy to explain if you need clarification, but im not gonna preemptively explain every single thing, i don't know what you already do or don't understand

naive pawn
steel wagon
naive pawn
#

and what about the other thing?

steel wagon
#

🔔Get Quiz Game Asset :
➡️ https://grafikgames.com/unity-quiz-game-template

In this unity quiz game tutorial for beginners, you will learn how to create a Quiz Game in Unity. Follow along as we go step by step to make a Quiz Game with 4 Replies in your Unity game. From setting up the project to implementing game mechanics, you'll gain v...

▶ Play video
naive pawn
#

ok... and do you have compile errors

steel wagon
#

yeah

naive pawn
#

then that's why

cosmic dagger
shut swallow
#

oh nvm im stupid

#

lol

steel wagon
lilac cape
#

What if you copied your code from your original QuestionManager and pasted it in a new monobehavior script?

#

Ahh nvm, you already said there were compile errors

#

If you're still having issues please share code 🙂

shut swallow
#

I have a coroutine trying to listen to a variable in a singleton timestopTriggered but when I try to do yield return new WaitUntil(() => !GameManager.Instance.timestopTriggered); within the coroutine, nothing happens, why?

    {
        visualEffect.playRate = 0.05f;

        yield return new WaitUntil(() => !GameManager.Instance.timestopTriggered);

        visualEffect.playRate = 1f;
    }```
cosmic dagger
cosmic dagger
shut swallow
#

not triggered, but have this error instead

#

context:

            {
                var hit = Physics.BoxCast(
                    center: castCenter,
                    halfExtents: vector3HalfExtents,
                    direction: slashDirection
                    );
                VisualEffect slashvfxinstance = Instantiate
                    (
                    vfx_slash,
                    position: castCenter,
                    rotation: slashDirectionQuaternion,
                    parent: root

                    );
                Destroy(slashvfxinstance.gameObject, 1);
            }
            else
            {
                var hit = Physics.BoxCast(
                    center: castCenter,
                    halfExtents: vector3HalfExtents,
                    direction: slashDirection
                );

                VisualEffect slashvfxinstance = Instantiate
                (
                    vfx_slash,
                    position: castCenter,
                    rotation: slashDirectionQuaternion

                );
                SuspendSlashes(slashvfxinstance);
                Destroy(slashvfxinstance.gameObject, 8);
                
                
            }
            ```
keen dew
#

and which line throws the error?

naive pawn
shut swallow
#

Do I need to attach the visual effect component?

naive pawn
#

what do you mean by "attach"?

#

it seems you've already set the reference?

naive pawn
keen dew
shut swallow
#

thought of something stupid

shut swallow
# keen dew
                (
                    vfx_slash,
                    position: castCenter,
                    rotation: slashDirectionQuaternion

                );```specifically, in the else part of the if...else
#

when I instanciate it's not valid

#

regardless of if the code is running if or else

keen dew
#

And what type is vfx_slash?

shut swallow
#

Visual Effect

shut swallow
naive pawn
#

try clearing the slot and dragging vfx_slash back in, i guess?

shut swallow
#

doesn't fix that the coroutine doesn't run tho

naive pawn
#

you never started it

#

you need to pass it to StartCoroutine

shut swallow
#

oh lol oops

spice hollow
#

any recomended site or literature to study the latest unity6 urp shader program library?

shut swallow
acoustic belfry
#

hey, when i update the values of the values of the code of an actor/prefab, how i can update the actor to have them as well?

naive pawn
#

what do you mean by actor exactly?

proud flume
#

Hi everyone! I’m working solo on a Unity project inspired by Black Emperor — it’s a fast-paced 2D side-view motorcycle game where the player glides up and down a winding road, trying to stay alive by keeping the bike on-screen and on-road. I've attached a video and screenshot of the code.

Core Mechanics:
The road scrolls from right to left (bike stays mostly centered).
Player can move the bike up/down and accelerate.
If the bike goes off-road, it slows down.
If it falls off the back or front of the screen (too slow or too fast), it's game over.
I'm using trigger-based detection to see if the player is on-road or off-road using tags like "Road" and "Game Over".

The Issue:
I’m using multiple modular road segments, each with a BoxCollider2D marked as Is Trigger.
I check for OnTriggerEnter2D to set bikerIsOnRoad = true and OnTriggerExit2D to flag off-road and apply slowdown + dust FX.
But when the player moves from one segment to the next, the OnTriggerExit2D from the old segment fires before OnTriggerEnter2D on the new one — so it wrongly triggers my “off-road” effect, even though they’re still on the road.
I’ve tried a buffer system (like checking for a short delay) and also using a roadContactCount to track how many road colliders the player is in. Still not quite right.
Has anyone faced this before? What’s a clean, Unity-friendly way to handle overlapping/adjacent trigger zones in a scrolling tile-style system like this?

Bonus Question:
Would you recommend designing the full road in something like Photoshop and slicing it, or building it directly in Unity using tilemaps or road segment prefabs?
My gut says Unity would be easier for adjusting difficulty and randomness later, but I’m curious how others approach this — especially for curving, procedural-ish 2D tracks.

Any advice or references welcome — thanks in advance!

wintry quarry
barren pelican
#

Hi everyone! I imported a Unity project from a zip file and everything works fine. Now I want to use Unity Recorder to create a 3-minute video from my scene. I'm using Unity 2022.3.5f1c1 and Unity Hub 3.3.3.

Can someone guide me on the best Recorder settings or check if I'm missing anything?
Thanks in advance! 🙏

proud flume
timid salmon
timid salmon
sinful hawk
#

Hey there! Not entirely sure if this is the correct place for this, but it seems like an easy enough (or should be easy enough) thing to work around.

I'm using an Event Trigger on an object I instantiate on runtime. I've checked that I have an event system running, and other Event Triggers on objects in the UI seem to be working quite well. For whatever reason though, the method I am calling here in the Event Trigger isn't getting called.

The *below screenshot is during Play mode.

Could this be some weird UI Image Layering issue? The crafting menu uses Event Triggers for when the mouse hovers over it, and I'm wondering if maybe that is getting in the way or if it's something else

#

Using a Debug.Log() to check if the method was called has shown me that the method just isn't getting called whatsoever

#

I also figured it may have been something to do with the sprite mesh, but the Image component is not using the sprite mesh, so the entire square area used by the object should be active and responsive for such a task

wintry quarry
#

Also are you definitely doing a full click-and-release sequence while keeping the mouse over the object?

sinful hawk
#

Just the UI Image component, the Recipe script as mentioned in the Event Trigger, and the Event Trigger itself

wintry quarry
#

"Raycast Target" or "Blocks Raycast" is enabled on the Image?

sinful hawk
#

Raycast Target is enabled on the image

wintry quarry
#

Ok the most likely thing here then is some other object is blocking it

#

try disabling other UI elements in your scene until it starts working

#

the most likely culprits are:

  • separate canvases
  • any other UI that is lower in the hierarchy than this object
sinful hawk
#

I only have one canvas, and I have disabled every object outside of the parents of such object and it is still unfortunately not working

wintry quarry
sinful hawk
#

Oh-- it's just a TextMeshPro obj

wintry quarry
#

Can you try disabling that?

sinful hawk
#

It won't let me for some reason while I'm paused in the game view

#

I will say though that it only covers beneath the ui image, so it shouldn't be getting in the way whatsoever

wintry quarry
#

Another thing to check is try pulling it out of the scrollrect/mask situation

sinful hawk
#

alright bet lets see

#

Yup, that did it

#

The event trigger is triggering when it's not a child of the containers and such

#

Further update: Even when setting the parent objects to the Ignore Raycast layer (which raycasts are what I'm assuming the event trigger uses), the child object-- still set to the UI layer-- is still not receiving any of my clicks, and so I cannot get the event/method to trigger

#

Yeah I fr cannot figure out why this is happening

#

I can't really afford to take it outside of the scrollrect/mask with how I'm setting this up

lilac cape
#

Is it normal to have a OnLookPerformed and OnLookCanceled for a Look action in my action map? Or should I just do something like Mouse.current.delta.x.ReadValue() in void Update? a I'm having an issue where my view keeps spinning without touching the mouse about 20-30seconds into playtime.

  // Action: Look
  [SerializeField] Transform cameraTransform;
  [SerializeField] float mouseSensitivity = 1f;
  float xRotation = 0f;
  Vector2 mouseInput;
 void OnEnable()
  {
    // Enable action map and actions
    playerInputActions.Player_OnLand.Look.performed += OnLookPerformed;
    playerInputActions.Player_OnLand.Look.canceled += OnLookCanceled;
 
    playerInputActions.Player_OnLand.Enable();
    // Lock cursor
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
  }
void Update()
  {
    // Get raw look input (mouse delta)
    float mouseX = mouseInput.x * mouseSensitivity;
    float mouseY = mouseInput.y * mouseSensitivity;

    // Clamp vertical camera rotation (pitch)
    xRotation -= mouseY;
    xRotation = Mathf.Clamp(xRotation, -90f, 90f);

    // Apply vertical rotation to the camera
    cameraTransform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

    // Apply horizontal rotation to the player (yaw)
    transform.Rotate(Vector3.up * mouseX);

    mouseInput = Vector2.zero;
  }
 // ===[Look Input Action Callbacks]===
  void OnLookPerformed(InputAction.CallbackContext ctx)
  {
    mouseInput = ctx.ReadValue<Vector2>();
  }

  void OnLookCanceled(InputAction.CallbackContext ctx)
  {
    mouseInput = Vector2.zero;
  }
wintry quarry
#

For continuous style inputs, this is often the case

lilac cape
wintry quarry
#
void Update() {
  Vector2 lookInput = playerInputActions.Player_OnLand.Look.ReadValue<Vector2>();
  // the rest of your code
}```
#

just one line of code instead of like 5 + variable + two functions

lilac cape
#

That's what I was starting to think but I like the structure of having a method(s) for each action😂 Is it common to not have methods for actions?

wintry quarry
#

The other option here is to set this action as a pass-through

#

then you only need to subscribe to performed

lilac cape
#

because the pass-through only takes continuous input and never sees a .canceled?

wintry quarry
#

Passthrough simply fires off performed for any change in the actuation of the control.
Value has a bunch of logic deciding if any given change in actuation should fire off started, canceled or performed depending on the interactions (or default interaction) on the action

sinful hawk
lilac cape
#

Thanks again for the Update method suggestion. Just tested things and mouse bug is gone. Now time to figure out why I can only open my interact/open my door on the door hinge. Maybe I might just cheese it and extend the colider around the child door object to see if that makes the interact box bigger

sinful hawk
wintry quarry
sinful hawk
#

Would the Event Trigger on the Container for all of the scrolling elements possibly be interfering?

wintry quarry
#

absolutely yes

#

EventTrigger is unfortunately kind of a sledgehammer

#

It subscribes to ALL of the UI events, and then silently ignores the ones you don't have listeners for

#

it's less intrusive if you make a custom script with only the ones you care about, e.g. cs public class MyClickListener : MonoBehaviour, IPointerClickHandler

lilac cape
#

Actually the mouse issue is back lol. For some reason whenever I open this door and leave, the mouse starts to spin. Maybe my interact script is messing with things?:

  void Update()
  {
    Vector2 mouseInput = playerInputActions.Player_OnLand.Look.ReadValue<Vector2>();
    // Get raw look input (mouse delta)
    float mouseX = mouseInput.x * mouseSensitivity;
    float mouseY = mouseInput.y * mouseSensitivity;

    // Clamp vertical camera rotation (pitch)
    xRotation -= mouseY;
    xRotation = Mathf.Clamp(xRotation, -90f, 90f);

    // Apply vertical rotation to the camera
    cameraTransform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

    // Apply horizontal rotation to the player (yaw)
    transform.Rotate(Vector3.up * mouseX);
  }
  {
    // Example: Raycast from the camera to interact with objects in front of the player
    Ray ray = new Ray(cameraTransform.position, cameraTransform.forward);
    RaycastHit hit;
    float interactDistance = 3f; // Adjust as needed

    if (Physics.Raycast(ray, out hit, interactDistance))
    {
      // Check if the hit object has an interactable component
      var interactable = hit.collider.GetComponent<IInteractable>();
      if (interactable != null)
      {
        interactable.Interact();
      }
    }
  }```
#

Even though when I standstill, the Vector2 debugging as (0.00, 0.00) but the rotation.y keeps incrementing(potentially 1unit per frame). I've tested in game-view multiple times and it seems like the rotation.y is always positively going up when it's bugging out. I'm not seeing the rotation.y decrease in value. I'm starting to think that if the Vector2 input has a x,y value greater than 90 or less than -90, it bugs out the mouse input

#

I think I have a fix that probably isn't the best solution. If I enable the xyz contraints on the player, the player mouse movement doesn't bug out and slowly rotate at times. So I think that means something in my physics is causing the slight turn

#
void FixedUpdate()
  {
    if (moveDirection != Vector3.zero)
    {
      float runSpeed = isSprinting ? MoveSpeed * sprintMultiplier : MoveSpeed;
      Vector3 direction = transform.right * moveDirection.x + transform.forward * moveDirection.z;
      Vector3 movement = direction * runSpeed * Time.fixedDeltaTime;
      rb.MovePosition(rb.position + movement);
    }
  }
acoustic belfry
#

what differences exist between
rb2D.linearVelocity and rb2D.MovePosition

rich adder
lilac cape
#

Is this a good idea for keeping the project organized? I have a door that I created in unity (not fancy, just using primitve shapes and basic material) and this is how I organized the animaitions, materials, and scripts. Is this a good organization strategy for objects that have an animation, material, and script?

acoustic belfry
brave robin
rocky canyon
lilac cape
#

Making a door open one way is easy. Making it open both ways is a whole nother level lol

real grail
# lilac cape Making a door open one way is easy. Making it open both ways is a whole nother l...

Learn how to implement doors in Unity! In this video you'll learn how to make:
⚫ Rotating Usable Doors
⚫ Rotating Automatically Opening/Closing Doors
⚫ Sliding Usable Doors
⚫ Sliding Automatically Opening/Closing Doors

You'll also learn how to make the rotating doors open AWAY from the player, instead of always opening only one directio...

▶ Play video
real grail
worldly oasis
#

hi has anyone experience with VR controllers? i have bit hardtime with them as i have no idea how their inout works

rocky gale
#

Praetorblue been helping people for decades

#

Crazy

worldly oasis
eternal needle
worldly oasis
eternal needle
#

or are you sure the code is running, and the position is where u think it is?

worldly oasis
eternal needle
# worldly oasis

do you see it in the scene view? it should always appear there at least

worldly oasis
#

wich is annoying bc in other projects i can see it using the same emthod

#

for some reason ihave only this problem when i use the VR built

eternal needle
# worldly oasis nope

well then the first thing id do is make sure the code is even running, maybe log the position while you're at it

#

then check if you see it in the scene view. you can put the game view side and scene view side by side

lilac cape
#

Am I on the right track here? I'm trying to make a door that can always open away from the player

using UnityEngine;

public class SingleDoorControl : MonoBehaviour, IInteractable
{
  private Animator animator;
  private bool isOpen = false;
  private bool openedForward = false;

  [SerializeField] private Transform playerTransform;
  [SerializeField] private Transform doorForwardReference;

  void Awake()
  {
    animator = GetComponent<Animator>();
  }

  public void Interact()
  {
    if (!isOpen)
    {
      Vector3 toPlayer = (playerTransform.position - transform.position).normalized;
      float dot = Vector3.Dot(doorForwardReference.forward, toPlayer);

      if (dot >= 0)
      {
        animator.Play("SingleDoorOpen_Backward");
        openedForward = false;
      }
      else
      {
        animator.Play("SingleDoorOpen_Forward");
        openedForward = true;
      }

      isOpen = true;
    }
    else
    {
      if (openedForward)
        animator.Play("SingleDoorClose_Forward");
      else
        animator.Play("SingleDoorClose_Backward");

      isOpen = false;
    }
  }
}
rocky canyon
#

just a glance seems ur on the right path..

#

either ur on this side -> positive
or that side <- neg

#

then just swap out the conditional as needed if u happen to get it backwards 😄

simple hawk
#

trying to make a top down shooter, but I can't figure out how to make the character shoot, the tutorials I'm finding use the legacy input system and I can't get my head around the new one

rocky canyon
#

b/c u can swap.. and/or use both even its just a setting

simple hawk
#

tbh, I have no idea how to do it for either, I never actually used the input systems for myself, I've just been watching tutorials and have no idea how they work

rocky canyon
#

well its worth learning the new one..

simple hawk
#

I will, is there a resource for me to do so?

rocky canyon
#

if u dont.. or would rather wait.. u can always swap it to the new one later when u feel mor comfortable.

#

i use Both in the project settings so i can learn as i go

#

its not completely deprecated yet 😄

#

as for resources.. i dont really know of any off-hand.. b/c theres soo many ways to do inputs so theres soo many different resources

lilac cape
simple hawk
#

also, how come people use [SerializeField] instead of Public? I get that the former doesn't let scripts access others, but why is that important?

lilac cape
# simple hawk tbh, I have no idea how to do it for either, I never actually used the input sys...

I've only been learning unity for a little less than a month now and the new inputsystem takes a long time to understand. For basics, I believe your action would be something like:
Action: Shoot
|-> Left-Click (Action Type = button)

Then something like:

using UnityEngine;
using UnityEngine.InputSystem;

public class Shooter : MonoBehaviour
{
    private PlayerInputActions inputActions;

    void Awake()
    {
        inputActions = new PlayerInputActions();


    }

    void OnEnable()
{
    playerInputActions.[YourActionMapName].Shoot.performed += OnShootPerformed;
}
    void OnDisable()
{
    playerInputActions.[YourActionMapName].Shoot.performed += OnShootPerformed;
}

    void Shoot()
    {
        Debug.Log("Bang!");
        // Add shooting logic here (instantiate bullet, play sound, etc.)
    }
}
floral wren
# simple hawk also, how come people use `[SerializeField]` instead of `Public`? I get that the...

In software systems, encapsulation refers to the bundling of data with the mechanisms or methods that operate on the data. It may also refer to the limiting of direct access to some of that data, such as an object's components. Essentially, encapsulation prevents external code from being concerned with the internal workings of an object.
Encaps...

lilac cape
# simple hawk also, how come people use `[SerializeField]` instead of `Public`? I get that the...

use [SerializeField] when you want your variable to be editable within the inspector but still private. Public allows the variable to be used outside the class and should be used only be used when needed because you can only have 1 public variable with that name. So if you had a public speed variable, now you can't declare another variable with the name speed.

I wanted to make sure I added as much info as possible so I sent your question to copilot as well. Here's that response:
Why use [SerializeField] private instead of public?
Encapsulation:
Keeping fields private means only the script itself can change them. This protects your data from being accidentally changed by other scripts, which helps prevent bugs and makes your code easier to maintain.

Inspector Visibility:
[SerializeField] lets you edit the value in the Unity Inspector, just like a public field, but keeps it hidden from other scripts.

Cleaner API:
Other scripts only see what you intentionally expose (via public properties or methods), making your codebase easier to understand and use.

Best Practice:
It’s a core principle of object-oriented programming to hide internal details and only expose what’s necessary.

Summary:
[SerializeField] private gives you the best of both worlds:

Editable in the Inspector
Protected from outside scripts
Cleaner, safer code
Use public only when you want other scripts to access or modify the field directly.

simple hawk
#

that makes sense, thnx for the help

simple hawk
#

lol

polar acorn
#

If it's not supposed to be edited from another script the best way to ensure you don't do it out of lazyness is to make it impossible

ivory bobcat
lilac cape
#

also if you don't specifically declare the variable as private, the default access modifier is private so the variable will still be private. Same thing for methods.

private void Shoot(){}

is the same as

void Shoot(){}

lilac cape
simple hawk
#

not really, getting a bunch of errors, not sure what they mean either

eternal needle
lilac cape
#

oh the bracket is your input action name is the name of your action map

simple hawk
#

some of this stuff, it's saying, does not exist

lilac cape
naive pawn
#

you have extra closing braces and the random [] in the middle of your script

#

the [YourActionMapName] thing isn't valid. you're supposed to put your action map name there, without the brackets

lilac cape
#

this will be the name of the input system you created then create a field (I usually do the same name as the inputsystem but with camelcase) to store an instance of your input actions

simple hawk
naive pawn
lilac cape
#

Correct, you're right, but should be the same name as the inputaction

#

Good catch

ivory bobcat
naive pawn
scarlet skiff
#

im gonna have enemies that deal damage on attack and collision, some only via attack, some only via collision, the thing is, if i enable a hitbox that is a child of the enemy as the attack, that still just counts as one and the same type of collision as if you walked into the enemy. to distinguish between those two attacks, im thinking ill have two physics layers, one for enemy body and one for enemy attacks, for enemy body, it has ontriggerstay2d logic with a cool down, and for the hitbox, that one can be triggerenter, is this a good solution or am i wasting a physics layer here?

naive pawn
#

there are 32 available layers, that'll be fine

scarlet skiff
naive pawn
#

what else are you gonna have

scarlet skiff
naive pawn
#

you wouldn't separate fire type attacks from water type attacks, you'd have a separate, more flexible system for that

lilac cape
naive pawn
lilac cape
scarlet skiff
# naive pawn no, i mean, what other layers are you gonna have was vague mb

its might be a big project, there is a lot of concepts that i wanna add that i havent broken down to unity implementations yet, so i cant say for sure how many ill need, im careful with my use of layers, so probably not many, and considering enemies are like very central, i dont usppose two layers for them is a waste. currently i only have ground, and GroundBound layer and player layer

naive pawn
#

the technically right way would probably be "input actions asset" but "action map" "input map" "input actions" would all work - just not the entire system

naive pawn
lilac cape
naive pawn
naive pawn
scarlet skiff
lilac cape
agile helm
summer forum
#

helloo, quick question, i was following this brackeys tut and he did not use a refrence object like he always did but used the findobjectoftype thing because he said that when tho playerobject was reset the refrence would be lost. Then to reset the scene and the object he used this built in method that saved the refrences, now im wondering why did he use the findobjectbytype and not create a refrence object in the first place?

grand snow
#

Its hard to actually understand from your message but perhaps it was to be more beginner friendly?
Finding by type isn't too bad if done sparingly to init a scene or some object.

wintry quarry