#💻┃code-beginner

1 messages · Page 797 of 1

junior saddle
#

for a state machine, over the network

#

I want examples because my brain is not braining, I can't think of handling player inputs and a state machine over the network

thank you in advance for the help 🙂

#

since there are so many updates and stuff happening, having this script on each player would be chaotic...

I can't wrap my head around it

marble kindle
#

I'm hoping maybe someone can give me pointers as to what in the heck I'm doing wrong here. The enemy is supposed to approach the train when they touch the ground.

As it stands, the code I have is thus

" private void Movement()
{
Vector3 targetRotation;
targetRotation = new Vector3(player.transform.position.x - transform.position.x, 0f, player.transform.position.z - transform.position.z).normalized;
enemyRB.AddForce(Vector3.forward * speed, ForceMode.Impulse);
}"

when I place this inside my fixedUpdate it works as intended. Great.

But when I move it into an if block, it stops working entirely and the enemy just stands there.

effectively this makes it stop working

" private void FixedUpdate()
{
GroundCheck();

    if (onGround == true)
    {
        LookAt();
        walkState = true;
        Movement();
    }
    else
    { 
        walkState = false;
    }
}"

The groundcheck works. the bool clicks on. I must be making some minor mistake somewhere. Can anyone tell me what I am doing wrong?

naive pawn
#

!code

rich adder
radiant voidBOT
marble kindle
#

I also tried setting onGround to toggle on and off manually, so like, that's still not doing it. It'll look in the correct direction, but the addForce never seems to take.

#

I halfway wonder if it's because I'm using a wheel collider for the enemy to slide around on, but that should theoretically still work inside an if block.

rich adder
marble kindle
#

The skeleton. it has one so it can slide forward and back towards the player.

#

Other code functions in the IF block. Just not the addforce(Vector3.forward) bit.

rich adder
marble kindle
#

Why does it work outside the if block but not inside it?

#

That's the thing I'm trying to figure out.

#

Because it functions 100% as intended outside the if statement.

#

I'm not actually influencing the wheel collider. I'm just adding force to the rigidbody.

rich adder
#

if it only works outside if statement, its pretty straight forward

marble kindle
#

Yeah. I'm just... If it's "If onGround == true" and it doesn't work even if I manually toggle that on and off, the conditions are being met.

marble kindle
#

Which is the entire problem. It can't be my raycast to groundcheck not working.

#

In the editor. Also in code. I tried both ways.

rich adder
#

put log inside the code itself and double check

#
Debug.Log($"onGround ? {onGround}");
if (onGround){
            Movement();
marble kindle
#

Yeah. Debug.Log pops up just fine.

rich adder
#

uncheck Collapse if needed

marble kindle
#

Collapse? Edit: Oh. Collapse. Got it.

#

It says it's registering as true.

#

Yet my movement still doesn't work inside an if block.

rich adder
#

!code

radiant voidBOT
bold panther
#

Hi, I have a question regarding unity and supabase (or any db hosted services). Basically I need to make a game that makes use of a database, So i created a supabase account and created the db and setup the authetification system. Now to communicate with my service, what do i need to do exactly? Do i need to setup an api, download an sdk or dlls, etc. I am very new to all of this and any help would be greatly appreciated!
Basically what i want to do is retriever a plyer state, which would store player data and scene number

rich adder
#

you should never have any information about your database like connection strings inside your unity Game or anything Local

marble kindle
#

Think I did this correctly. It's a little sloppy. First project and all.

#

Well, first in Unity anyways.

bold panther
rich adder
marble kindle
#

Oh darn it. It was working right. I had the mass on my npc set to a stupid number. Oh I'm so sorry for bothering you. Thank you for taking the time to deal with me not looking at everything in my project.

#

There's no need for a skeleton to weigh 1000kg.

rich adder
#

that mass is crazy high, also kinda threw me off that with same mass you said it was working without if or you changed mass after >?

marble kindle
#

Yeah. I'm thinking it only worked before because the NPC started spawned in the air and had no friction or resistance so could build momentum before it landed. I had it all messed up!

bold panther
#

but thanks for the extra ressources

rich adder
#

thats all the API is, common function that perform an operation

#

"I want to give player X , 100 credits"

call myappurl/giveCredits?100 with proper verified auth token and do the thing

nocturne pond
#

Hey everyone so im making a top down 2d game in unity and i want to make a simple setup where i can shoot an enemy, he takes damage eventually dies after 10 hits, and he also shoots projectiles to me and damages and can kill me so i have the shooting system for both the player and enemy setup but they arent dealing any damage to eachother for a reminder im a beginner and i have done most of my code with ai help and right now im stuck because even ai doesnt know what the problem is😭 heres a small video of what it looks like so far

bold panther
#

so if i get this right, in unity i will only use libraries for networking and io, and use the api, the supabase will do all the work related to the db and authetification right?

rich adder
bold panther
#

alright now this makes way more sense omfg

#

istg all the videos i saw

#

were talking about installing an sdk

#

and adding the right dlls and all

#

even gpt was tweaking

rich adder
#

there might be an SDK available for supabase but probably third party..

bold panther
#

thanks a lot for clarifying thins man

bold panther
#

which makes it even more a pain

rich adder
#

the point is, you never want to store directly information about your database in unity

#

anything that lives on the users PC can be decompiled

#

they would know your databse keys and insert their own data or worse, corrupt / overload it

bold panther
#

i mean wouldnt the anon key and the project url be safe to expose?

#

form what i read only the secret key needs to be kept private

rich adder
#

you should have control over it at all times, I would never store any keys locally if it has an SDK that can handle certain things with a public key then its different but you still need proper auth

#

its less likely that user could get keys if you have those stored on a server app

#

all they see if they decompile your local project is that you make Get requests etc.. pretty useless to them

bold panther
#

true true

#

well man thanks a lot for ur time fr

#

i rlly appreciate it

#

uve been more helpful than anything ive seen lol

rich adder
#

np. n goodluck.
Remember to start small, lock in the concepts and slowly go into a bigger scale

#

start with API with no Database and only stores in memory, then move into doing extenral database talks

nocturne pond
#

Hey nav sorry to bother you but you seem like you know how to programm well any chance you could help me with the problem i have?

rich adder
#

the video doesn't work

nocturne pond
#

oh

#

wait

#

one sec

#

lemme do a yt link

rich adder
#

jus make it mp4

nocturne pond
#

idk how

#

yt link is easier dw

naive pawn
#

use an mp4

rich adder
#

did you use OBS it has built in converter

naive pawn
nocturne pond
#

k lemme do that

civic palm
#

how do you define a unity input system input map in code?

#

if i wanted to reference it in start for example

naive pawn
#

you would construct it, i imagine

#

ok, do you want to define one, or do you want to declare a variable to reference one

nocturne pond
rich adder
naive pawn
#

are your layers set up correctly

nocturne pond
rich adder
nocturne pond
#

wait im so sorry guys i have to go eat i can give all those infos in like 20 minutes ill be back im so sorry again

naive pawn
#

is it not set up correctly now?

civic palm
rich adder
civic palm
#

i think it made a script for it yea

#

Called PlayerControlls

#

Player Controll Inputs

#

im not rly sure

rich adder
civic palm
#

i am just wondering is there code to reference an action map

#

so i can disable/enable it

swift crag
#

There's no InputActionMapReference, annoyingly

#

I've thought about trying to make one myself

civic palm
#

even if my script that uses input system is disabled, it will continue doing inputs for it

swift crag
#

you can, of course, find an action map from an input action asset

civic palm
#

oh i see i see

#

so could i reference that and disable the map part of it?

rich adder
#

you could use InputActionAsset and find it there

#

I just generate a C# class from it so its easy / type safe

#

this way you can do
MyCustomActions myCustomActions
myCustomActions = new()
myCustomActions.Enable()

#

myCustomActions.Player.Shoot etc.

#

just dont name it anything unity has like common mistake is PlayerInput cause it collides with the component

civic palm
#

the script generated by the input asset has a bunch of errors on it

civic palm
#

not sure why it like dat

rich adder
#

are the errors also in unity console

civic palm
#

ya

#

lots of errors

nocturne pond
rich adder
#

why do you have PlayerControllerInputAsset and PlayerController

nocturne pond
civic palm
#

hold up

#

i figured it out

rich adder
civic palm
#

i had a duplicate of the script in another folder

rich adder
#

thats probably why it errors

civic palm
#

or from another one of the input actions i had made in the past

#

whoops

#

@rich adder the script has no errors now, but i am not sure where to go from here

rich adder
nocturne pond
rich adder
#

the big problem is you wrote none of this and let something write slop for you which you understand none of

nocturne pond
#

i can understand prob 50 percent of it

rich adder
#

you start with learning the basics , then work your knowledge up so you can actually put pieces together you can easily understand

nocturne pond
#

so im not skilled enough to make this game yet right?

rich adder
#

put it on pause and start simpler

nocturne pond
#

also i dont understand how is this code that bad like could you give me examples possibly?

nocturne pond
rich adder
#

where you wrote all the code and know each line

rich adder
#

lots of redundant / outdated functions too

nocturne pond
# rich adder where you wrote all the code and know each line

okay that makes since I did this because i do the same thing as all beginners i think i can make a big project but end up failing i just dk how to like actually learn and start cuz ive done like 5 of unity's tutorial games and i remember like none of it and i cant code a single thing basically

nocturne pond
rich adder
#

thats a good step

nocturne pond
nocturne pond
rich adder
#

if you start small, in no time you will get to bigger projects

#

if you start big right away, you will crash and burn quick

nocturne pond
#

like functions

rich adder
#

learn nothing because you most likely didnt practice enough what you just learned, especially on your own without the guidance of the tutorial

#

You cant / should not move on the next lesson if you didnt practice and can repeat what you learned on your own

nocturne pond
#

how did you start coding?

rich adder
#

I started with modding HalfLife with some C++ then realized the same thing (hit limits of low knowledge)

#

started small with unity and c# and built up knowledge

velvet lantern
#

hihi! hopefully simple to answer, but how would i reference the "source image" field of this component in c#? I'm relatively used to working with gameobjects but haven't done much with UI yet, and need to change the sprite of this section of the UI to display the player's health

#

every tutorial I find online seems to reference either an older version of unity, or uses a method i can't adapt ^^;

nocturne pond
naive pawn
rich adder
#

right. Like "How to move an object"

#

not. "how to make movement like zelda etc."

#

try to be more generic

velvet lantern
#

thank you !

rich adder
#

when i started it barely existed

nocturne pond
nocturne pond
rich adder
#

in a nutshell its used to give you consistent values between diff framerate speeds

#

if you did timer += 1 in update, your timer goes up faster on higher FPS
if you did timer += 1 * Time.deltaTime it increases the same speed no matter the fps
deltaTime is the time in seconds it took since the last frame processed

nocturne pond
naive pawn
#

you don't have to think mathematically, no

nocturne pond
rich adder
nocturne pond
naive pawn
#

you have to think logically, and keep the cyclic nature of Update in mind

rich adder
#

c# itself is just a tool / language to accomplish something,
Unity gives you API (functions and whatnot) to maniupulate its engine

rich adder
#

Update and such are Unity concepts not necessairly c# related

#

you learn them through the manual

nocturne pond
#

so API is kindof to link the coding and the gamengine to make the code work as functions right?

rich adder
#

its a common language you can use to communicate with the backend

nocturne pond
rich adder
#

in this case c# was chosen

#

its like a telephone number you can dial local to get connected to a bigger system

nocturne pond
#

okay

rich adder
#

the original engine is written in c++

nocturne pond
#

so if i want to start learning right now what tutorial or whatever should i do right now?

nocturne pond
rich adder
#

probably because c# is much much easier to pickup

nocturne pond
rich adder
#

learning traditional c# is important, objects, logic flow, types etc

#

it seems boring and basic, but pays dividends

nocturne pond
nocturne pond
rich adder
#

thats the learning curve aspect, but its pretty low not steep

#

thats why you balance it with unity, so its a bit more fun

nocturne pond
rich adder
rich adder
#

seeing object move because you learned how to manipulate values is satisfying

nocturne pond
#

alright well tysm you were an amazing help to me im looking forward to speak to you again if i need any more help

gloomy loom
#

could someone please help me 😭

rich adder
gloomy loom
#

alr

#

does ANYONE here know how to delete a unity package?

#

im new to unity

naive pawn
#

have you tried like, googling that

gloomy loom
#

yeah

naive pawn
#

it's a pretty general question, google will have plenty of answers, and it'll be faster and easier than asking and waiting tbh

#

package manager -> remove package

#

if it's locked, it can't be removed because some other package is using it

gloomy loom
#

ahhh...

#

ty

#

im tryna use photon, i messed it up lol

rich adder
#

you're doing multiplayer but don't know how package manager works, ouch

gloomy loom
#

:[

nocturne pond
#

hey so nav can you make like mods for games or like plugins for any game with C#?

civic palm
#

i am struggling to get the input action maps to actually disable when i have the script referenced in my code, I have the script referenced in my code (1st image) and then when the script is disabled/enabled it should turn the input maps on and off right? am i doing something wrong?

#

movement is my action map

rich adder
civic palm
#

just tried it and when it was disabled it did put a log

#

idk why it wont disable my input map, it so confusing

#

i have an action that involves clicking but it still lets me do it even with script disabled

rich adder
civic palm
#

yea

#

all other inputs also enabled not just click

rich adder
civic palm
#

in a script called movement, i have a function for each action that gets the inputs and makes player move/jump/dash

#

that is also the script where i enable and disable the stuff, should i make it seperate perhaps?

rich adder
#

if you planning on disabling / enabling on demand you should track in one spot

civic palm
#

i do have two states that the player can be in (normal 2d controls a powerup that changes controls), so maybe i could put that in the script that deals with swapping states?

rich adder
#

You could always verify that the actionamp is enabled / disabled with a log as well

#

Debug.Log($"is movement enabled ? {PlayerControllerScript.Movement.enabled}");

#

verify its actually disabling it when you do / before using it

civic palm
#

it says false

#

thats so strange

#

i have to be overlooking something maybe

rich adder
#

probably. you should also show where you utilize these actions in code

#

make sure you're linking the correct map

civic palm
#

i found a dumb way to do it

#

i just disable the player input component

#

baboom

#

idk if thats a good way to do it tho

rich adder
#

you were using PlayerInput in the first place ?

civic palm
#

is that a bad idea to use the player input component?

rich adder
#

its not but you should not use both

#

you shouldn't be mixing them thats prob why you got odd results

civic palm
#

wait i am confused

rich adder
#

if you already have a generated class from the ActionMap, you don't need the PlayerInput component at all

#

PlayerInput is mainly used if you use Inspector to link Actions or/ using the SendMessages modes

civic palm
#

ok so wait, if i am using the player input component on my player object, should i not worry about using the script generated from the action asset

#

or should i get rid of player input component and change how my player controls work? i have been using that to get my controls, by adding events that are triggered by code

rich adder
#

your IDE doesn't look configured peoperly ? are you even getting the intellisense suggestions

civic palm
#

yea im not sure, how can i set up the intellisense stuff correctly

radiant voidBOT
# rich adder !vs
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

civic palm
#

i think im gonna stick to the player input component

royal monolith
#

Hi, trying to make a track which is flat and goes around in 1 loop but this little junctions keeps happening. Could anyone help me? Thanks in advance.

queen adder
broken nest
#

Has the image component changed? Why do I have to manually set my assets to 2d sprite?

rich adder
#

not a code question.
and they made it sprite- multiple for default sprites so dragging the root in a sprite field doesn't work, you need to change it back to single

queen adder
#

It's sarcasm.

solar hill
royal monolith
#

Oh 😂 yeah I am kinda fried been at this for some time 😂😂😂

solar hill
#

if you are going to comment on someones issue try to actually help

red igloo
solar hill
#

if youre still moving up when you decide to slam it could counteract the downward force causing it to be slower

#

youre not i just checked

#

do that and see if the issue persists

red igloo
solar hill
red igloo
lethal meadow
red igloo
solar hill
#

and you should try doing what i suggested

#

you also dont have to overcomplicate it like you did it in your jump script, im pretty sure you can just do

rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0f, rb.linearVelocity.z);
#

add this to both of your slam methods.

#

also why are your slams 2 seperate functions at all?

red igloo
solar hill
#

you should keep it as a single function and just parameterize it

high anchor
#

Is there a good tutorial going over the in-engine variables (object parameters and such) and going into detail on how to find and use them?

wintry quarry
#

"in-engine variables (object parameters and such)" is way too vague to be meaningful

high anchor
#

It is extremely vague, yes. I'm kind of taking a shot in the dark.

Let me try to narrow it down...

wintry quarry
#

Can you explain what you're trying to do? Just learn to be comfortable programming in Unity?

#

Have you looked at !learn?

#

!learn

radiant voidBOT
high anchor
#

Yes. Problem is, I have no idea what I'm actually looking for and I don't really want to skim through 'over 750 hours' of stuff to figure it out.

So let me see if I can try and get an example of where I'm stuck...

swift crag
wintry quarry
swift crag
#

this happens because the two nearby spline points have very large weights

#

they both want to push the spline very hard

#

so it kinks up

high anchor
# wintry quarry You don't skim through all of it. Start with the junior programmer pathway to ge...

So, I know 'the basics of scripting'. I have an associate's degree in programming. (And then I never got a job because I live in the middle of nowhere and was unable to compete for remote work and am now about two years rusty, minus some playing around on CodeWars to keep a modicum of basic skill up)

My problem is, I don't know how to, say, get the variables that govern the size of a game object into a script so that I can then have it make another game object change in size proportionally whenever that first object's size is changed.

solar hill
#

the junior programmer pathway isnt just there to teach you coding, if youre new to unity you still stand to benefit from watching them

#

as they will teach you unity specific stuff* like this

high anchor
#

(It's arguable exactly how much that 'keeping up a modicum of basic skill' actually worked, but here we are)

solar hill
#

but other than that what you are actually looking for is the unity api

swift crag
solar hill
#

you also still need to learn to use the editor itself

swift crag
#

for example, this explains what GameObjects are and how they work – including Transforms

wintry quarry
#

But "size of a gameobject" could mean anything from its scale, to the extents of its renderer bounds, to something custom in the context of a particular game

swift crag
#

yes, that needs to be clearly defined first (:

#

a game object does not have a "size"

pastel cave
#

I believe what they're asking is literally being able to attach a setter to the transform component

wintry quarry
pastel cave
swift crag
#

The "core" of Unity is closed-source C++

high anchor
#

Scale is what I was referring to. Please forgive me, I'm mildly stressed out by the fact that I'm having as much trouble as I am.

Thank you for the help so far. I at least feel like I have an idea of where to work from now.

wintry quarry
swift crag
#

Many of its features are implemented in packages, which are mostly C#

#

for example, UGUI (the Canvas-based UI system) is all in a package you can go look at and modify

pastel cave
#

I see

swift crag
pastel cave
#

Mhm, I've gleamed as much

#

That's good to know, though

boreal ingot
#

guys i am trying to make multiplayer into my game and its really just messing it up. i decided to have copilot help me with this but i can t get a sync correctly andd everytime i get copilot to try and fix it i feel like it makes me code really bad. anyway thats something i have to manually fix laster going throught all the code to see what bs it did but now what i want is some help to sync it correctly so the game can work. i have been at this for 5 hours i really need help would appreciate a call

solar hill
#

theres no voice channels here, if you need help you should share what you did, what you are trying to do, any relevant code etc.

#

be as detailed as possible

boreal ingot
teal viper
broken nest
#

Hey, why can't I make a list of a struict?

polar acorn
#

Why not what's stopping you

broken nest
#

I get an error CS0308

slender nymph
#

show your code

broken nest
#

Why did it disappear ><

teal viper
broken nest
#

I legit pasted some code and it disapeared

#

magic

polar acorn
#

Did you format it properly

#

!code

radiant voidBOT
naive pawn
#

probably just took a little to refresh

meager siren
#

How would one use OnPointerEnter?

#

Cause im trying to add a visual upgrade system that pauses the game (Sets timescale to 0 after a level up). Ive done it but I can't seem to well. im using oncollision enter and the pointer handler thing for the script isnt working

#

hard to explain

#

for me atleast

twin pivot
meager siren
rough granite
# meager siren wdym?

Unity's docs have no matches with OnPointerEnter are you certain it's a thing? (i swear i've heard the thing but like there are no docs for it), also i think they mean what is the interface it's from

meager siren
#

oH

#

I needa check that

teal viper
#

There is in the ui package docs.

meager siren
edgy tangle
#

You need the IPointerEnterHandler interface

meager siren
#

how would I get it?

edgy tangle
#

You need to implement the interface. Similar to marking a class inheritance

teal viper
meager siren
#

it didnt tell me :p

teal viper
#

Who??

meager siren
#

internet

#

Or I just didnt well. Look hard enough ig

rough granite
edgy tangle
#

public class MySuperCoolClass : MonoBehaviour, IPointerEnterHandler

meager siren
slender nymph
#

now you need to correctly implement the method

teal viper
meager siren
rough granite
slender nymph
teal viper
edgy tangle
meager siren
meager siren
edgy tangle
#

The error is telling you you have implemented the interface but have not implemented its requirements

slender nymph
# meager siren

it's not a member of the inherited class. just right click the interface name and use the quick actions to implement it

meager siren
#

Man I needa learn unitys particle system badly

meager siren
#

OHH

#

I SEE WHAT YOU MEAN

#

Now imma hope this actually works :p

rough granite
slender nymph
#

it's in the UI package docs because it comes from the UI package

teal viper
#

3.0 was probably a discarded experimental version.

meager siren
#

does it matter that scripts on an empty gameobject?

#

nvm

slender nymph
#

yes that matters. if this is a UI object it needs a graphic to work. if it is world space it needs a collider

meager siren
#

I figured out why I just dunno how to fix it without removing the crosshair

meager siren
slender nymph
#

make sure your crosshair is not a raycast target

meager siren
#

alright

#

that would make sense

#

there we go

#

thank you again boxfriend

meager siren
#

random unity encounter???

cosmic dagger
cosmic dagger
#

i used to change it more often, depending on the season, but it was RandomUnityXXX . . .

#

"XXX" was replaced with smth different, but this has stuck for a while . . .

meager siren
#

You love your dotpoints dontcha?

#

are they even dot points or am I crazy

cosmic dagger
#

it used to be ... but they gave me an upgrade to . . .

meager siren
#

😭

#

Now I wanna make my display name something like yours

cosmic dagger
#

you'll find smth that fits. give it time . . .

sacred thorn
#

Hey im new to game development and i just for the life of me figure out how to make a slide function for pistols and if anyone can help me out a bit heres the code of one version out of many of my attempts
using UnityEngine;

public class SlideRack : MonoBehaviour
{
private Vector3 startLocalPos; // husker startposition
private Quaternion startLocalRot; // husker rotation
public float slideLimit = 0.2f; // hvor langt ned X kan trækkes

private Transform grabTransform;

void Start()
{
    startLocalPos = transform.localPosition;
    startLocalRot = transform.localRotation;
}

void LateUpdate()
{
    // Lås rotation
    transform.localRotation = startLocalRot;

    // Lås Y/Z og kun bevæg X
    Vector3 pos = transform.localPosition;
    pos.y = startLocalPos.y;
    pos.z = startLocalPos.z;

    if (grabTransform != null)
    {
        // Håndens position i parent-local-space
        Vector3 handLocal = transform.parent.InverseTransformPoint(grabTransform.position);

        // Kun X, clamp mellem start og start - slideLimit
        pos.x = Mathf.Clamp(handLocal.x, startLocalPos.x - slideLimit, startLocalPos.x);
    }

    transform.localPosition = pos;
}

// Kald dette når hånden griber objektet
public void Grab(Transform hand)
{
    grabTransform = hand;
}

// Kald dette når hånden slipper objektet
public void Release()
{
    grabTransform = null;
}

}

meager siren
#

InverseTransformPoint?

#

whats that?

sacred thorn
#

it tells you where the point is in relation to this object.

meager siren
#

huh

#

that would be pretty useful im suggesting?

sacred thorn
#

basically it translate world space x,y and z too local space of an object

meager siren
#

Yeah this just tells me that I needa learn more stuff

hushed pagoda
meager siren
#

oh

#

we dont use that anymore. I think you can enable the use of it again

#

but we use

#

hold on

#

this stuff now

#

and this

#

But I am sure you can definintly re enable the old one

#

im not sure though

hushed pagoda
#

what to do then?

slender nymph
#

!input

radiant voidBOT
# slender nymph !input
How to Set Input

To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling

• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.

meager siren
#

I knew you could enable it somewhere

hushed pagoda
#

ty ill ty

hushed pagoda
#

unity hub or unity

meager siren
#

unity

#

at the bottom where its highlighted (somewhat)

hushed pagoda
#

what to do now

meager siren
#

hold on I was doing something

hushed pagoda
#

ok

meager siren
#

In othersettings change the active input handling

#

to the old one or both

hushed pagoda
meager siren
#

then click apply at the bottom

#

dont forget that. Idek if it reminds you

hushed pagoda
#

it restarted when i did

#

ty for tell i am struck there for 3 days

#

if u dont mind can u tell differ b/w = and ==

meager siren
#

==

#

is checking if the variable is equal to whats on the right side

hushed pagoda
meager siren
#

you can use it for other things like

#

if (integer == 1)
{
Do this
}

#

For bool variables you can just do
if (boolVariable) - Checks if true

if (!boolVariable) - Checks if false

hushed pagoda
#

ok one more thing where can i learn code

meager siren
#

oh

#

Well.

#

Idrk?

#

So its either you learn it from Unity Learn

#

which is useful

#

watch youtube videos, look at other peoples codes and searching up what they used and how they used it

#

its a bit. Weird if you dont have a school program for it

#

I do, they just dont teach C# :p

#

or an online course.

#

Like Code4Fun

meager siren
hushed pagoda
#

ill try those sources ty

rain solar
#

when generating terrain with fractal noise how do i interpolate between noise samples? when i do linear interp the terrain looks low quality cause its just a bunch of squares and i cant use bicubic because it creates wavy terrain

keen bridge
dark root
#

using UnityEngine;

public class paddlecontroller : MonoBehaviour
{
public Rigidbody2D padrb;
public float speed;
private float paddleInput = Input.GetAxis("Vertical");

void Start()
{
    
}
void Update()
{

    padrb.linearVelocityY = paddleInput * speed * Time.deltaTime;
   
}

}

#

Why doesn't this make my paddle move

#

I have no idea what I'm doing

chrome tide
night raptor
#

Also, I don't think you want to multiply the speed by deltaTime here. Often you want but in this case linearVelocity is already velocity in units/second and unity makes sure the object actually moves at that fixed speed regardless of the framerate. Multiplying by deltaTime here would do the opposite of what you want, it will make the object move at different speeds with different framerates

dark root
#

Thank you it works

final sluice
#

I made an Enemy script moving by following a path , after reaching each "Waypoint" , it will check if the relative distance between the enemy and the waypoint is 0 , if it is 0 and it isn't the last waypoint, it will keep moving.

It has been working super fine until now , for some reason the relative distance appeared that number whenever the Enemy reached SECOND waypoint. It's not even the first . I can't find a way to bybass it , I don't even understand what it is.

I use a spawner to spawn waves of enemies , which have been working fine until this happens . It also should be noted that if I drop a prefab of the enemy into the scene, its moving code work just fine. So I think it's a problem with the spawner, which I don't understand what it is since it's only job is to spawn stuff.

#

Pls help, im dying

#

This is the moving script

#

Is this a bug, or did I do something stupid

#

Please help aaaaaaaa

midnight plover
final sluice
#

THANK YOU, IT WORKS

stone oar
#

hey so I was trying to edit the bloom.active variable using a script to enable/disable bloom at runtime. toggling it via inspector in editor mode works fine, but as soon as i start play mode - even using inspector doesn't do anything.

i use volume.profile.TryGet<Bloom>(out bloom); in Start() method to get the bloom value out from the Volume volume component and then edit it via bloom.active = true/false. I can see the changes to the variable in inspector (aka the box ticks off) but it has no effect on the game itself.

BUT when I remove the TryGet line entirely - suddenly I can edit the bloom and all other post-processing effects in inspector in play mode. what's going on? all tutorials use this structure and i have no idea why i it doesn't work for me specifically

midnight plover
#

Show your entire script best case

stone oar
#
public Volume volume;
private Bloom bloom;

void Start()
    {
        volume.profile = Instantiate(volume.sharedProfile);
        volume.profile.TryGet<Bloom>(out bloom);
    }

void BloomSetting()
{
  bloom.active = false;
}```
#

its really nothing special

#

bloom starts turned ON and i just try to turn it OFF

#

i also tried the version without volume.profile = Instantiate(volume.sharedProfile) to no avial

#

it looked like this:

public Volume volume;
private Bloom bloom;

void Start()
    {
        volume.profile.TryGet<Bloom>(out bloom);
    }

void BloomSetting()
{
  bloom.active = false;
}```
midnight plover
#

and you dont get any errors?

stone oar
#

no

#

hm actually i do

#

NullReferenceException: Object reference not set to an instance of an object

midnight plover
#

well, your bloom is not working getting returned but you access it I guess

stone oar
#

right around the bloom.active = false;

#

so ig it just doesnt know what bloom i use

midnight plover
#

you can use the tryget inside an if statement to check, if the out is actually delivered

#

the bloom should be the one in your volume profile

stone oar
#

Bloom is out! Bloom(Clone) (UnityEngine.Rendering.Universal.Bloom)
UnityEngine.Debug:Log (object)

#

the bloom IS getting disabled but it has no effect on the game

#

bloom is still active

#

if i remove the TryGet then i can change the bloom in inspector just fine

#

but with TryGet - i cant even do that

stone oar
midnight plover
#

Then I guess the error might be, that your bloom is not the correct one. Its targeting not the instantiated profile

#

which script are you using now. The instantiated or the simple one?

midnight plover
stone oar
stone oar
#

manually in inspector not through code

midnight plover
stone oar
#

same result

midnight plover
#

When is BloomSetting() called?

balmy vortex
#

hi can you use gameObject.activeSelf to check if scripts on game objects are active too? or is it only for the actual game object itself?

midnight plover
stone oar
midnight plover
# stone oar when i press a button

what happens if you try inside the method

if(volume.profile.TryGet(out bloomComp))
  bloomComp.enabled = !bloomComp.enabled;
else
  Debug.Log("No bloom");

Not tested the code, if there are any typos 😄

stone oar
#

does not work

#

also its .active not .enabled 😅

ivory bobcat
stone oar
#

well ill be damned but intellisense says otherwise

#

'Bloom' does not contain a definition for 'enabled' and no accessible extension method 'enabled' accepting a first argument of type 'Bloom' could be found (are you missing a using directive or an assembly reference?)CS1061

ivory bobcat
polar acorn
harsh tartan
#

Hey im missing something, im following https://learn.unity.com/pathway/junior-programmer/unit/basic-gameplay/tutorial/lesson-2-1-player-positioning?version=6.0 and im at step 7, but it doesnt work anymore?

using Unity.Mathematics;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float horizontalInput;
    public float speed = 10.0f;

    public float xRange = 25.0f;


    public GameObject projectilePrefab;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (transform.position.x < -xRange)
        {
            transform.position = new Vector3(-xRange ,transform.position.y, transform.position.z);
        }


        if (transform.position.x > xRange)
        {
            transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
        }




        horizontalInput = Input.GetAxis("Horizontal");
        transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
        }
    }
}
``` its trying to move  but keeps getting stuck at 0 0 0, and when trying to move the max position is gonna be -0.1
what did I do wrong?
Unity Learn

Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.

rich adder
#

try higher number

harsh tartan
#

at the player its at 10 but will try 40

rich adder
harsh tartan
#

now it works but now the border isnt working as I can go futher t hen 25.

And why does it work on 40 and not on 10?

harsh tartan
keen dew
#

xRange is the border... if you set it to 40 then you can go up to 40

#

The number 25 in the code is the default. The value you put in the inspector is what it uses

harsh tartan
#

check thanks

rancid tinsel
#

is it possible to do something like GetComponent<(Image || CustomImage)>().value as long as both of them have the value field?

naive pawn
#

no, C# doesn't have union types in that way.

#

the type system is nominal, not structural

#

they'd need a common parent that has that field

rancid tinsel
#

I see, thank you!

crude jungle
#

Hey guys, I'm trying to apply the new Input System to some old navmesh tutorials. I've been through a lot of the documentation regarding the new Input system, I've checked previous posts on reddit and the Unity site and even searched for an answer in the Discord chat here. I saw someone using these .performed/.started/.canceled methods with their input controller, but mine don't seem to have a definition for it.

I've messed around with the input actions editor a bit to see if I could find anywhere that these methods were mentioned, which didn't work. In the example given, they also didn't provide any other context other than "this will work", so I don't really have any other key information to google at this point.

Is anyone able to shed some light on these by any chance? Cheers, tried to provide as much context as possible!

steel sapphire
#

hi guys, have a very generic question
how can i make track for bike racing type game. if possible please share some resource, i couldn't find proper resources

rich adder
#

You can use common methods like Spline tools, unity has one built in or get an asset purposefully built for roads

steel sapphire
crude jungle
steel sapphire
#

also thinking about, how the unity will render such a large map? does unity automatically takes care of optimization?

rich adder
rich adder
#

You have to code these in, and there is minimal optimizations for objects not in view but thats about it, the rest must be optimized by you

#

road redemption is made in Unity so its totally doable

#

thats the closest I've seen to a road rash clone

crude jungle
steel sapphire
#

correct me if you can think of a better idea

rich adder
#

its usually the "middle" part so you can kinda figure in the width of each lane / road itself to get more accurate / consistent result

rich adder
# steel sapphire cool thanks,

basic ointro + sample unity includes for roads
https://youtu.be/FbSvEieELXo

more complex code/parts like figuring points on the road etc.
https://youtu.be/ZiHH_BvjoGk?t=328

Let's learn how to make Roads using (Custom Mesh) in Unity using the Unity Splines Package!

Get my Spline Mesh Package (It's FREE) 👇
https://github.com/AnanD3V/SplineMeshUnity

****** IMPORTANT ******

⚠ A BIG UPDATE has been made to the package ⚠

You can now download the Git version of the package, and install it directly from the Pack...

▶ Play video

Roads are more common in videogames than you might think so in this episode we'll look at how we can use Unity's new spline package to build out a tool that procedurally creates a road mesh along a spline, and ALSO handles intersections at the same time. While we're at it, we might even decorate it to look pretty using URP Decals too!

Get the p...

▶ Play video
broken nest
#

Hello, I'm trying to build a tree, how can I do that? I was trying to make a recursive struct but that doesn't work

#

How does a gameobject can contain another gameobject as a field for instance

frosty hound
#

You can use whatever component is on that other GameObject as the type, or just use GameObject

broken nest
#
{
    Node node;
}

public struct NodeStruct
{
    NodeStruct node;
}```
Why does the first one work but not the second one?
rich adder
#

it has no idea what size it needs to store it, reference types you're storing a pointer and they generally have a set size

#

computer: How big is NodeStruct?

answer: It needs the size of node,
But node is another NodeStruct
which contains another NodeStruct
which contains another NodeStruct

… forever, so needs infinite size

broken nest
#

Ok thanks a lot that makes sense

swift crag
#

To understand recursion, you must first understand recursion 😉

charred spoke
#

Oh I have a meme for this but can’t post it here

frail hawk
#

thank god there are loops

balmy vortex
#

hi is 1f from Time.deltaTime actually equal to 1 real world second?

#

cuz it feels way slower for some reason

charred spoke
charred spoke
rich adder
slender nymph
charred spoke
#

And electro gremlins

balmy vortex
swift crag
#

notably, if the game hitches for long enough, Time.deltaTime is clamped

#

the default limit is 1/3 of a second

#

that's probably not causing issues for you, though

night raptor
#

I thought that 1/3 second cap only applied to physics but that seems to similarly apply to max value for deltaTime. Makes some sense, but the tooltip and documentation weirdly enough only talk about physics there. One of those poorly documented features

swift crag
night raptor
#

No links or mentions of the Scripting API equivalent

civic palm
#

im having a really annoying issue with my 2D platformer, im trying to get a drilling mechanic working correctly. Basically when my character dashes it makes a hitbox that when coming into contact with surfaces on a certain layer, you enter a drill mode that toggles another hitbox that waits for OntriggerExit2D to detect if that collider has exited. Randomly my drill mode instantly swaps me back to my normal 2D platformer controls when entering a surface and i have been trying to find the solution for ages

if any coding genuises would be okay with potentially getting into a voice call and i could screenshare id be okay with that, i feel it would be hard to get help with just images

naive pawn
#

we don't do vc's here, it would negate the benefits of having a community server to begin with

#

you can share screen recordings to show your issue if needed

civic palm
#

oh yea sure

#

i shouldve done that xD

#

i can send

naive pawn
#

i won't be free in a few mins, so just some general tips - play around with the mechanic a lot in various scenarios, different terrain, different angles if that's a factor, etc - try to find what the common denominator is, to then reliably reproduce the issue
from there, debug to see why the issue is occuring, possibly drawing debug or gizmo stuff to make sure stuff is lining up as it should

swift crag
#

Maybe you're exiting a collider that you didn't expect to be there

#

The bug could depend on how many frames you get between each physics update (by defualt, physics runs 50 times per second)

civic palm
#

i can send a video of my code if needed

swift crag
#

share your code with one of these sites

#

!code

radiant voidBOT
civic palm
#

cool website

#

here is my code

swift crag
#

I see that you set swappingStates to true until the next fixed update. You aren't currently doing anything with that variable

#

my first suspicion is that the drill and dash colliders don't quite match

#

i noticed that you instantly exited drill mode while moving upwards

#

If you want to check if every element matches, you can either:

  • iterate over them and compare each element
  • use LINQ
#

nooo the question vanished

#
int[] foo = new int[] { 1, 2, 3 };

if (foo.SequenceEqual(new int[] { 4, 5, 6 }))
{
    
}

here's an example of using LINQ; it provides the SequenceEqual method

#

comparing for exact equality wouldn't be useful, since it'd just tell you if they were the same array

#

(i think, at least; i haven't really thought about the array equality operator before...)

#

also, the reason you got an error was that {1, 2, 3, 4, 5} isn't an array: it's syntax used when constructing an array

#

but it's not valid on its own

#

Newer versions of C# do have array literals, like this:

#
int[] foo = [1, 2, 3];
#

but not the version that Unity uses

civic palm
#

also does ontriggerexit tend to trigger twice perhaps?

swift crag
#

no, it only runs once each time a pair of colliders stop overlapping

swift crag
civic palm
#

okay wait i just found something out

#

i can send clip

#

i realized that the drill always fails when the exit collider is positioned at the direction of the surface you drill into

#

at the start of the game the drillcollider is in the center of the player but after one time it always is where it last was upon exciting a drill mode

#

could that be important?

#

the green circle on the right side if the collidr

#

ok im testing it a bunch and that is for sure the issue or one of them

#

i am confudsed why it causes issues

#

is it because first frame is outside of wall? before hitbox is positioned to front

civic palm
#

this is gonna drive me craaaazy

civic palm
#

i think stuff breaks when the collider for drill and movement are overlapping upon entering drill state

#

but i dont know what to do to fix it, its just one gets enabled and one disabled simple as

stone oar
#

the wonders of programming :]

swift crag
#

annoyingly, trigger messages don't tell you what your collider was

#

only the other collider

thin lotus
#

how can I use the variable float speed = 0.1f; for the X value in transform.position += new Vector3(0.1f, 0, 0);?

swift crag
#

I'm not sure how this works in 2D physics. In 3D physics, if an object has a Rigidbody, it receives trigger messages caused by child colliders

swift crag
#

the Vector3 constructor takes 3 float values

#

those can be literals (0.1f) or variables (speed)

thin lotus
#

but it gives me the error "Assets\Movement.cs(4,7): error CS0116: A namespace cannot directly contain members such as fields or methods"

#

line 4 defines the variable

civic palm
polar acorn
thin lotus
polar acorn
thin lotus
#

oh wait im dumb

#

oh

swift crag
#

fields are declared inside of a class, yes

thin lotus
#

thats a really dumb mistake i knew that

#

lol

slow blaze
#

I'm trying to make a type of node for mining which have a class that essentialy boils down to

class Node{
string nodeName;
int extractionValue;
int extractionSpeed;
}```
now this class is called in anothere monoBehaviour Object to make an instance of it

```C#
class MiningNode : Monobehaviour{
Node node;
//rest of code
}```
I want to manually set the nodes in the world, how can I manually give each object of the MiningNode prefab have different values in the node objeect through the editor?
would scriptableObjects be a better fit for this?
civic palm
# civic palm

im trying and trying and there is a slight change i might have found the issue, its the drill collider that is causing issues somehow but i dont know how

eternal needle
swift crag
#

yeah – use a ScriptableObject if different prefabs can meaningfully refer to the same set of data

slow blaze
swift crag
#

in this case, I feel like each prefab is going to have a completely unrelated set of mining data

slow blaze
eternal needle
#

oh i think i misread

slow blaze
eternal needle
#

it doesnt sound like you'd really gain or lose anything here making it a scriptable object regardless

#

even if there's a direct 1 to 1 relationship between prefab and instance of this node SO. I like making things like this an SO just cause it's cleaner to see in github tbh

slow blaze
#

I see
thanks for the insight

pastel cave
#

I am finding Unity's rules for physics increasingly nonsensical.
A Collider2D.Cast can't collide with things that don't have a RigidBody2D component. This is somewhat sensical.
But if the GameObject that HAS the collider has a RigidBody2D component, now suddenly it CAN collide with things that don't have a RigidBody2D component?

#

What is the logical throughline here I am missing

polar acorn
#

Rigidbody is the component that actually calls the physics engine. If there's no Rigidbody involved no one has access to the physics engine for collision detection.

Whenever any sort of collision happens, each object has a reference to the other, so either one can have the Rigidbody on it

#

The physics engine knows about all of its rigidbodies, and can basically ask "okay any of my rbs getting hit by something? No? Any of em doing the hitting? Ah, okay cool"

pastel cave
#

so I simply made a Ball that doesn't use RigidBody2D

polar acorn
#

Then you're going to need to do your collision detection without the physics engine using primitive shape casts

#

Or use a kinematic Rigidbody that you have full control over

pastel cave
swift crag
pastel cave
#

nope doesn't need one
or I've been hallucinating that my project works this entire time lmao

pastel cave
#

it also can't be made to move programmatically

polar acorn
#

A kinematic rigidbody is unaffected by forces and only moves when you explicitly tell it to in code

pastel cave
#

it's unaffected by forces, yes. But it seems to move exactly once every FixedUpdate and there isn't a method to force it to move

#

at least that I found

#

I could be wrong. My research wasn't during the hours of the day when one is completely clearminded

#

wait, no, I think there was a slide method

polar acorn
pastel cave
#

but a slide isn't what I need

grand snow
#

If unhappy with the physics time step increase it

polar acorn
#

And you "force" it to move by calling MovePosition

pastel cave
#

Oh?
How's that work

grand snow
#

📖 read da docs

pastel cave
#

it collides with things between where it currently is and the target of the MovePosition?

polar acorn
#

That's literally the way you're supposed to move a kinematic rigidbody

#

If you did anything but that, then you weren't actually using a Kinematic rigidbody

pastel cave
#

I see... What a strangely named method

#

let me double check that this is usable for me

#

Mmm. Is GetContacts only for overlaps or is it anything that the MovePosition Collided with last fixed update?

#

since it seems to still penetrate statics

#

but I might be able to give this another shot

#

assuming collisions are ordered sensibly...

pliant dome
#

I moved a gameobject with a box collider into a parent and the animation for the collider is broken. Is there a way to tell unity where it is or do I have to redo the keyframes all over again?

grand snow
pliant dome
#

Oh nice thank you

civic palm
#

@swift crag i fixed it!!!

#

took SO LONG

#

mostly fixed

#

still a bit buggy but its not deadass random

#

The main issue was the usage of ontriggerenter/exit2D

#

when the collider is teleported (so basically every fixedupdate for the drill collider) it will trigger the enter/exit

#

i also abandoned using tags to detect in/out and switched to using fixed update for both colliders and detecting a layer on a child object of the ground instead

#

ok its not fully fixed but it works because it starts drill -> cancles -> starts again so it works in a goofy way

#

will def have to solve that

fallen mural
#

can someone check the scripts ive written for my enemy? this is my first project so im not rlly sure if this is the correct way to do stuff since I have 5 scripts and 5 children for a simple enemy that just patrols, follows the player in a straight line if in sight and attacks if close enough
idk if should send them here since theyre long and theres 5 of them

#

this is 2d btw

prime goblet
fallen mural
#

alr i js wasnt sure if i should send it here since its a lot

#

this is what my hierarchy looks like

#

i feel like what ive done is a rlly suboptimal way to do it and i dont want to develop bad practices for future projects

teal viper
radiant voidBOT
#
<:error:1413114584763596884> Command not found

There's no command called vode.

teal viper
#

!code

radiant voidBOT
wintry quarry
#

they do almost entirely the same thing

fallen mural
#

but maybe i was js doing it wrong

drifting cosmos
#

am i correct about this If i use Physics2d.Raycast the raycast wont be scene isolated it will raycast through all scenes but if i save a reference to the scene and call it isolatedscene then do isolatedscene.Raycast then will it be scene isolated?

rich adder
drifting cosmos
# rich adder for that you need to grab the `PhysicsScene` not the regular `Scene`

so just do something like this ? Scene currentScene = gameObject.scene; and isolatedscene = currentScene.GetPhysicsScene(); will it work with my physics simulator object thats in my scene that has this script on it ```public class PhysicsSimulator2D : MonoBehaviour
{
private PhysicsScene2D _physicsScene2D;

private void Start()
{
    Scene currentScene = gameObject.scene;
    _physicsScene2D = currentScene.GetPhysicsScene2D();
    Debug.Log($"PhysicsSimulator2D started in scene {currentScene.name}");
}

private void FixedUpdate()
{
    if (_physicsScene2D.IsValid())
    {
        _physicsScene2D.Simulate(Time.fixedDeltaTime);
    }
}

}```

drifting cosmos
rich adder
#

I think that setting only affects default scene?

mint imp
#

Idk if this is "beginner" exactly but i had a query for you wizards.
What would be an effective way to make swappable abilitys

RIght now im running code through scriptable objects that i can drag and drop into my "ability slot" for whatever ability i want to be using.
but my abilities are more complicated then i hoped.

What is the standard approach
Abstract class for ability that every ability devives from? then i just drag and drop the ability component into my object, and remove the old ability?

Im not sure

naive pawn
#

that doesn't sound super great for doing at runtime

#

keep in mind your SOs can also have methods

timber tide
#

They don't need to derive from a base, but you do need some sort of abstract method that they all share at least.

golden notch
#

if only unity had code backups. i went and made a window manager and it crashes the game and editor with no visible errors when i click the chat 🤦‍♂️

slender nymph
#

that's what version control is for.
but also, if i had to guess you probably have an infinite loop or infinite recursion somewhere

golden notch
#

yeah i did an if statement and it fixed the crash, but it's still not working properly

slender nymph
#

if you want help then you'll need to be more specific than "not working properly" and you'll have to provide relevant context

golden notch
#

i will when i know more

north kiln
#

Calling the console "chat" is very cursed

sour fulcrum
#

Setting the console to emote only mode

pastel cave
dusty umbra
#

Guys never use public fields

#

I beg you

north kiln
#

yeah never do it (doing it at least 2,149 times)

fickle plume
#

@dusty umbra Please don't post off-topic images

limpid thistle
#

public class GyroUI : MonoBehaviour
{
    [SerializeField] private float shiftModifier = 10f;

    private Gyroscope gyro;
    private RectTransform rectTransform;
    private Vector2 startPos;

    void Start()
    {
        gyro = Input.gyro;
        gyro.enabled = true;

        rectTransform = GetComponent<RectTransform>();
        startPos = rectTransform.anchoredPosition;
    }

    void Update()
    {
        float x = gyro.rotationRateUnbiased.y * shiftModifier;
        rectTransform.anchoredPosition = startPos + new Vector2(x, 0f);
    }
}

I want to have a parallax effect when i build this game on my device, but i dont see anything hapenning when i build it and run it on my android tablet.

Does anyone know what im doing wrong?

midnight plover
limpid thistle
#

No, my laptop doesn’t have a gyroscope

livid anchor
#

Not really a code question but does anyone know why the animation I made with the animation tool doesn't work on my tmp text ?

midnight plover
midnight plover
livid anchor
limpid thistle
limpid thistle
livid anchor
#

How do I force start an animation on a specific gameobject ? What do I need ? The animator controller ?

livid anchor
#

No I mean in code

chrome tide
#

the object will need an animator controller.

livid anchor
#

I think i'll need to work more on animations....

midnight plover
limpid thistle
#

Nope just using old input system, I also double checked the tablet I’m running should have a gyro, but could not find it anywhere in the settings. I have the galaxy tab A9+

midnight plover
#

Also you could install a third party app for testing sensors just to be sure, applications can read from your device

limpid thistle
midnight plover
limpid thistle
limpid thistle
#

api does this Input.gyro.enabled = true;
instead of this gyro.enabled = true;

midnight plover
true flame
#

Right so i am just testing out a piece of code. So when the player collides with the enemy, it should show a message in the log. But it isn't working. Any ideas or suggestions?

limpid thistle
naive pawn
harsh tartan
keen dew
#

It's feasible and up to date. As with many other things there is no "best"

harsh tartan
keen dew
#

Why would the official tutorial teach something that isn't usable

#

Instead of stressing about what way is better than another just start with something

tight fossil
#

im using RotateAround...Vector3.back for the left one which works fine, but the right one is using V3.forward (because using V3.back would just make it go in the same direction as the left one) which i assume would work if I could set it's starting point further along the rotation path. How would I go about doing this?

#
            {
                swordGameObject.transform.RotateAround(gameObject.transform.position, Vector3.back, Time.deltaTime * 100);
            }
            else
            {
                swordGameObject.transform.RotateAround(gameObject.transform.position, Vector3.forward, Time.deltaTime * 100);
            }```
is there maybe some sort of way to *-1 the rotation so it's mirrored?
midnight plover
#

Right now, you are moving within time. If you want to offset it first, dont use Time related values on init.

tight fossil
midnight plover
tight fossil
#

ok see the one on the left? i want it to do that but mirrored

#

the isFlipped == false is what's doing the one on the left, im trying to flip it so it does that with the one on the right

midnight plover
#

Okay, and just by using vector3.forward for both but one with 100 and the other with -100 does not do that?

tight fossil
#

no that's giving me the same as just using vector3.back

keen dew
#

It is mirrored, but on the diagonal. If you want it mirrored on the Y axis you can just rotate them so that they start upright (| instead of /)

tight fossil
#

i dont want them to start upright though it'd be too big a sword swing for what im trying to do 😭
i get what you mean though

sweet mural
#

I got a question

tight fossil
#

the starting point is the angle and then it goes either left or right

midnight plover
keen dew
#

But how is it going to be mirrored on the Y if they start leaning to the right

sweet mural
# midnight plover just ask...

sorry anyways I want to know if anyone can use c script for a vr game not sure what channel I’m supposed to put this in but mb

sweet mural
#

mb I’m new to unity

frosty hound
tight fossil
#

so it leans to the left

midnight plover
sweet mural
#

so idk

keen dew
#

You're going to have to first figure out how exactly you want them to behave

tight fossil
#

i do, i want the right one to lean left and move down, which i know vector3.forward will make it move down i just need to figure out how to make it start leaning to the left instead of right, which is why im here

keen dew
#

Yeah that's the question you should've asked in the first place

tight fossil
#

so do you know how?

midnight plover
#

You need to take your starting angle and from there add your rotation.

tight fossil
#

Yeah I know, that's what I'm asking 😭

keen dew
#

First rotate one of them to the place where you want it to start. Then look at the inspector and write down what the rotation is. Then add this code to Start:

if (us.isFlipped)
{
    transform.eulerAngles = new Vector3(x, y, z);
}

Put the correct rotation values in place of x, y and z

#

Bonus: use a Vector3 field so you can use the inspector directly

tight fossil
#

ok i need to understand why it's starting at that rotation in the first place im not setting it, and it's not starting at 0 or anything. is it because of the angle it's already in?

keen dew
#

What do you mean the angle it's already in

tight fossil
#

well when i start RotateAround the z-axis starts at around 60~ and I don't undertstand why the rotation begins there as both it and it's parents aren't close to that. In fact just changed the Z-axis of the parents and it changed nothing when it swiped the sword it's still starting at 60ish

midnight plover
tight fossil
#

the parents resting Z axis is -15 but even when I changed to anything else its still starting at that 60ish lean

#

everything else in the hierarchy is 0

midnight plover
tight fossil
#

exactly how it's leaning in that gif, it's parent "holster" is at -15 causing it to be slanted

midnight plover
tight fossil
#

yes

#

also just figured it out, i hate how bandaid it is but i cant sit here and fix this all day

midnight plover
#

is your sprite rotated?

#

Like the actual sprite file?

tight fossil
#

no it's straight

midnight plover
#

transform.rotation = 0,0,0 should be straight. But its not, unless you still have other scripts running

tight fossil
#

it's fine though i worked out a solution, just added a one time offset of 90 to the time.deltatime * 100

tight fossil
#

dont worry about it, its done now, thanks everyone for the help

midnight plover
tender mirage
#

I have no clue why but if i reference a another integer like "number" here i don't get a out of range array error but when i do use "i" i get an out of range array error even tho the int number literally equals to "i" beforehand

//Initialize offsets
float currentX = 0;
float currentY = 0;

for (int i = 0; i < colums; i++)
{

    //Spawn button
    GameObject characterButtonClone = GameObject.Instantiate(characterButtonPrefab, partyMembersObject.transform);

    //Assign position
    characterButtonClone.transform.localPosition = new Vector3(currentX, currentY);

    //Assign name
    characterButtonClone.name = "characterButton" + i;

    //Get text
    TextMeshProUGUI nameText = characterButtonClone.transform.GetComponentInChildren<TextMeshProUGUI>();

    //If party member exists
    if (i < lobbyParty.partyMembers.Count)
    {

        //Assign name based on party members name
        nameText.text = lobbyParty.partyMembers[i].characterName;

        //Get current character
        Character character = lobbyParty.partyMembers[i];

        //For some reason this works.
        int number = i;

        print(number);

        //Add button listener with delegate based on party member
        //If i put "i" here instead of "number" i get an error
        characterButtonClone.GetComponent<Button>().onClick.AddListener(delegate { PartyMember(number); });

    }
    //If no party member exists
    else
    {

        //Remove listenrs
        characterButtonClone.GetComponent<Button>().onClick.RemoveAllListeners();

        //Disable characterbutton
        characterButtonClone.GetComponent<Button>().interactable = false;

        //Assign empty
        nameText.text = "EMPTY";

    }


    //Add to current list
    currentCharacterButtons.Add(characterButtonClone);

    //Apply offset by width
    currentX += characterButtonClone.GetComponent<RectTransform>().rect.width;

}
#

I'm very confused

tender mirage
#

I see. So loops and delegates don't really go well together.

ivory bobcat
naive pawn
verbal dome
swift crag
#

It's a really sneaky problem

verbal dome
#

Rider does show a warning for that, at least

#

Probably other IDEs too

swift crag
tender mirage
swift crag
#

This is more of an issue with anonymous functions than with delegates in general

#

a "delegate" type is just a function type

tender mirage
#

I've heard that events were better to use then unity events. Is this also true with delegates vs events?

#

I apologize if that sounds out of field. I'm just very unfamiliar with delegates. You can probably read that.

swift crag
#

UnityEvent is very similar to a delegate-typed variable, except that it can be serialized and modified in the inspector

#

these two are very similar:

public event System.Action Foo;
public UnityEvent Bar;
#

(the event keyword allows anyone to add functions to the delegate object, but only allows the owning class to invoke it)

tender mirage
#

that could be great for learning delegates and understanding them better.

swift crag
#

but this is a vague memory

tender mirage
#

i should definitely mess around with that. Thanks alot for informing me.

tender mirage
swift crag
#

Having a UnityEvent exposed in the inspector is really nice for when you need to tie one-off things together

#

like when you want to add an extra particle effect to one enemy's attack

edgy tangle
#

UnityEvents wrap a delegate under the hood anyway

#

But they add the convenient inspector functionality

swift crag
#

not quite!

#

they store a list of invokable objects

#

rather than modifying a single delegate object

#

of course, a delegate object is, itself, just a list of things that you can invoke

#

Every time you modify a delegate object, an entirely new object is created. This makes it safe to add or remove targets from it in the middle of an invocation

edgy tangle
#

Oh so it doesn’t wrap a delegate declaration? I thought they did

swift crag
#

I'm not sure how UnityEvent behaves, by comparison, actually..

tender mirage
#

Wait, can unityEvents take parameters like delegates then?

edgy tangle
swift crag
#

e.g. UnityEvent<int> takes an int

edgy tangle
#

But, you are limited with Inspector functionality

tender mirage
tender mirage
swift crag
#
if (baseInvokableCallList[index] is InvokableCall invokableCall2)
  invokableCall2.Invoke();
else if (baseInvokableCallList[index] is InvokableCall invokableCall1)
{
  invokableCall1.Invoke();
}

what's going on here 😭

edgy tangle
#

Yeah that’s confusing lol

swift crag
#

gotta check twice, just to be safe

edgy tangle
#

I’ll take a look at the API later. Apparently I misunderstood how it works

swift crag
#

It's a really pedantic difference, to be fair

#

As far as you're concerned, it's just like having a delegate object

edgy tangle
#

But either way, I doubt that there’s any substantial difference in performance to use a C# event vs. a Unity event

swift crag
#

yeah

edgy tangle
#

Personally I like to just use them in the way of: event for something I want to happen only on the code side; UnityEvent if I expect to have some callbacks that any non-coder could easily set up with the Inspector

eternal needle
swift crag
eternal needle
#

I don't think im using unity event at all currently tbh, but thats just a preference

#

I do like actually seeing it in code

swift crag
#

I sometimes use both

tender mirage
#

good point honestly.

swift crag
#

a C# event for other code that always depends on the event, and then a UnityEvent for when I want to bodge something in :p

edgy tangle
#

Unity Events with Inspector callbacks are very convenient to set up but can be difficult to track down for debugging

eternal needle
#

compared to a script on the canvas which referenced every button needed and hooked up the event in code. I could at least click on the reference and be shown which button I was using

swift crag
#

yeah, most of my buttons work like that

#

it just winds up feeling better to me

midnight plover
#

I started making a reflection component that could hook every method that was available by singleton patterns. That way, I did not have to drag drop any reference into every button but just assign the correct method once. Made it easier for me to decouple hierarchy objects a bit

#

The reflection was only happening in editor mode and later on just the static Class.Instance was called if available

rain solar
#

when generating terrain with fractal noise how do i interpolate between noise samples? when i do linear interp the terrain looks low quality cause its just a bunch of squares and i cant use bicubic because it creates wavy terrain

swift crag
#

Your noise may have too high of a frequency

#

if bicubic interpolate looks really wavy, that means that your terrain wants to go up and down really fast

spare thunder
#

Is it normal that with an almost empty unity project it already takes me 16 seconds each time ?

frail hawk
#

when does that occur

rich bramble
spare thunder
#

Whenever I make a script change or test the sample scene.

#

I have a good computer overall

#

rtx 3060

#

I literally just added these

#

I never really worked on unity. any options I should be checking ?

humble bronze
#

Uhh do you have an SSD or a hard drive ?
i know that my projects were veryy slow when i had a hard drive

spare thunder
#

SSD

rich bramble
# spare thunder rtx 3060

It could be because Unity is a heavy editor Every new project loads a lot of things so it also opens slowly for me 🤔

humble bronze
swift crag
#

Script recompilation takes 3-10 seconds for me, depending on the project size

#

If most of the time is being taken up by asset imports, then that's a bit weird

#

You can go to Window > Analysis > Import Activity to look at recent import events

#

it'll show you how long each import took

#

e.g. a decently sized model took 2 seconds to import (i have some custom postprocessing happening, and it's...not optimized)

spare thunder
#

Hmm. how can I exclude some folders from import ?

swift crag
#

why do you want to do that?

#

are you seeing something taking a long time in the import activity window?

spare thunder
swift crag
#

most of these are just built-in shaders

#

they'll take a little while to compile, once

spare thunder
#

Seems like basic stuff, but I have uploaded some of my book's references (out of the assets folder though).

swift crag
#

Unity will only import things in the Assets and Packages folders

spare thunder
#

Hmm then it's weird

swift crag
#

nothing in here looks unusual

#

trigger another reimport and then look at the recent events

spare thunder
#

still 17s

swift crag
#

Don't sort by duration; sort by Last Import

#

that wil show you what's actually reimporting

spare thunder
#

weird, so it reimports everyrthing all the time even if they weren't changed ?

#

it makes no sense though, all the last imports account for like 3s

swift crag
#

Assets are only reimported if a dependency changes. Dependencies can be the file the asset comes from, other assets, project settings, etc.

#

what are you doing to trigger importing? are you changing a script file?

#

if so, that'll take a while (all scripts in the assembly, and any assemblies that reference it, must be completely recompiled)

#

you won't observe this in the importer window

#

Each import event will explain why the import happened

swift crag
#

the C# compiler isn't really something the asset import system understands

spare thunder
#

Yes, everytime I change a script from the 3d empty project I have to wait 17s already?

spare thunder
swift crag
#

that's a very long compile time for an empty project, for sure

spare thunder
#

So there must be a problem,

#

Creating a new fully empty project to test