#💻┃code-beginner

1 messages · Page 233 of 1

buoyant knot
#

you were told before to use the pastebin via bot. you were told again after ignoring the bot. Do not make that mistake again

polar acorn
#

Just use a bin

buoyant knot
#

quaternion.x does not mean an angle in x

thick jetty
#

what is a bin?

polar acorn
buoyant knot
#

read this

#

READ IT

#

man i wish i could post the gif of uncle ruckus forcing tom to read

thick jetty
#

i used the URL that was linked

#

is that the correct way to do that?

polar acorn
#

Yes now what is the actual issue?

buoyant knot
#

that looks like a pic to me on mobile

thick jetty
#

i am having some issues with getting a unit to walk, been trying to figure it out and watched videos nothing is helping. not quite sure what to do, my next thought was scrap and start over again. but i wanted some input first i created terrain and a unit as a capsul i also created a new layer called ground and i baked a navmesh surface into the terrain so that the unit can walk from my knowledge the code is correct i have double checked it and even re wrote it and that is doing nothing

buoyant knot
#

anyway, this will not work, because you are messing with the insides of a quaternion. which we keep telling you not to do

polar acorn
thick jetty
#

ok thanks. i will do that, where can i look in the editor for the log data. not new to programming. just very new to unity

rocky canyon
#

console

thick jetty
#

cool thanks did not see that it is small

buoyant knot
#

i read cornole

rocky canyon
#

cornhole

thick jetty
#

thanks now that you showed me there is a consol i am able to just debug it myself. appreciate it

#

Debug.Log("Hit: " + hit.collider.name) this is what i did. or is there a more specific thing i need to type for it to appear in the unity consol

rocky canyon
#

{variable}

odd widget
#

hello

graceful oriole
#

Hello, I tried to make a script to resize a grid layout (in ui scroll view) to fit any screen size. It works perfectly in the editor, but when I do a standalone build, it doesn't show the content of the grid layout (there is a list of prefabs and it shows only the root element of the prefab, but not it's children) Any ideas how to debug it?

RectTransform rectT;
    GridLayoutGroup layout;

    // Start is called before the first frame update
    void Start()
    {
        rectT = this.GetComponent<RectTransform>();
        layout = this.GetComponent<GridLayoutGroup>();
    }

    // Update is called once per frame
    void Update()
    {
        Rect rect = rectT.rect;
        float width = (rect.width + layout.spacing.x) / Mathf.Round((rect.width + layout.spacing.x) / (150 + layout.spacing.x)) - layout.spacing.x;
        layout.cellSize = new Vector2(width, width);

    }
#

I tried to but there new Vector2(100, 100) instead and it works (it doesn't do the resizing, but it renders all elements), but when I changed it to new Vector2(100 + width * 0, 100 + width * 0), it doesn't work anymore

#

Also, the width is probably right, because the width of the prefabs seems ok, but it renders just the gray rectangle and not the content inside of it.

graceful oriole
#

But for some reason, it still manages to make a difference

hot wave
#

is normalize ok to use when using character controller?

#

or is there a better method to make diagonals same speed

frosty hound
#

Normalizing is the way

hot wave
#

okok UnityChanSalute

unreal imp
#

this is in the shoot IEnumerator TrailRenderer trailRenderer1 = Instantiate(trailRenderer); Vector3 startPosition = muzzle.transform.position; //Quaternion startRotation = muzzle.transform.rotation; Vector3 endPosition = /*startPosition + */muzzle.transform.forward * shootRange; trailRenderer1.transform.position = startPosition; //trailRenderer1.transform.rotation = startRotation; trailRenderer1.Clear(); trailRenderer1.AddPosition(startPosition); trailRenderer1.AddPosition(endPosition);

short hazel
#

Trail renderers renders trails automatically as object moves, you don't need to set its positions. If you want to use poistions, use a Line Renderer instead.

hot wave
#

but cant understand what they meant on the solution

short hazel
# hot wave but cant understand what they meant on the solution

Basically, GetAxis does not immediately return say -1 when you press S, the value is smoothed out over a few frames. Same for when you release the key, it takes some time to go back to zero. So when you normalize, you have that remnant input until the value becomes exactly 0, and it can't normalize a zero-vector anymore
The solution is to use GetAxisRaw, that doesn't have any smoothing applied.

lost anvil
#

got this weird bug where if the player picks up an item the item gets added it to a list but when the player is moving and they try to remove it from that list it stay in the list and gives me that error at the bottom of the console

hot wave
#

I will use them from now on

strong wren
lost anvil
slender nymph
#

does vs code not differentiate types and methods in syntax highlighting or is this unconfigured

lost anvil
#

unconfigured probably i dont know my brother set all this up for me like a week ago

slender nymph
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

lost anvil
strong wren
lost anvil
#

yeah ive got the latest stuff

strong wren
lost anvil
#

no its just the base editor

strong wren
#

Does the error occur if you don't have this object selected when you repeat the steps?

lost anvil
#

what do you mean selected?

strong wren
#

Having some other or no object selected in the hierarchy

lost anvil
#

i thought my code was wrong, sorry about that

strong wren
faint sluice
#

@lost anvil btw since you're already implimenting IPickable interface, you can skip the CompareTag step by using TryGetComponent

strong wren
#

It is still a bit odd that something as basic as this is broken in a patched version of Unity. Did you make sure to actually start the project with the latest patch you downloaded?

lost anvil
strong wren
#

Unity editor stuff is quite extensible, so it's possible some thirdparty stuff you put in could be messing with some common Unity elements, but that's about as much I can say.

lost anvil
slender nymph
faint sluice
# lost anvil like TryGetComponent<IPickable>(); ?

Yeah, and out IPickable current in the prantheses

If object has Ipickable component on it it will return true as well as the reference to that component so you can directly call current.Pickup(); inside the if block

willow scroll
#

Hello, how do I get the size of the RectTransform in world coordinates?

slender nymph
#

why in world coords?

willow scroll
slender nymph
willow scroll
#

which involves getting everything in world coordinates to avoid issues with parent transform

faint sluice
willow scroll
willow scroll
#

This isn't a xy problem, just a question

willow scroll
slender nymph
#

and if you would bother explaining why you are trying to do this, a proper solution can be suggested

willow scroll
# slender nymph this does not make it any clearer why you are trying to do this

I am making a panel being dragged inside of its view rect. Now, view rect has its coordinates being get though its Rect, but these min and max positions aren't working properly when the object is being affected by its pivot or parent, which should be fixed (and is on the halfway of being fixed) by using the world coordinates

faint sluice
#

Scroll rect doesn't work for what you're trying to achieve?

slender nymph
#

why would using world space coordinates for UI objects suddenly fix your issue?

willow scroll
willow scroll
faint sluice
willow scroll
faint sluice
slender nymph
willow scroll
willow scroll
#

If you press the "minimize" button on any of your windows, it's going to become smaller than your screen size and you can drag it

#

that's what I define as "draggable panel"

timber tide
#

IDraggable interfaces not good enough?

willow scroll
willow scroll
timber tide
#

It's just a buffer that sets the current dragged object and then you move the element with the pointer

willow scroll
#

anyway, the logic is the same as mine

meager steeple
#

i have a problem where when i use a toggle to change to windowed, i close the game and open it again, its still in windowed but the toggle is set to fullscreen.

faint sluice
willow scroll
#

I used it before and found it better to simply use Input.GetMouseButton & Up, Down

desert moon
#

My bro is trying to make a character control system using a rigidbody. And it's nearly perfect other than the fact that it hangs up on walls. Anyone encounter something like that before?

rocky canyon
#

use a physics material with a low friction

slender nymph
willow scroll
# faint sluice Show how you're moving the object?
Vector2 potentialPos = _beginPos + (Vector2)_mainCamera.ScreenToWorldPoint(Input.mousePosition);

Vector3[] corners = new Vector3[4];
dragView.GetWorldCorners(corners);

Vector2 minPos = corners[0], maxPos = corners[2];

dragPanel.position = MathHelper.Clamp(potentialPos, minPos, maxPos);
#

now I've implemented it using world coords

cosmic dagger
willow scroll
tender stag
#

why is this happening? ```cs
float angle = isCrouching ? crouchLeanAngle : isCrawling ? crawlLeanAngle : walkLeanAngle;
float distance = isCrouching ? crouchLeanDistance : isCrawling ? crawlLeanDistance : walkLeanDistance;

if(canLean)
{
if(Input.GetKey(KeyCode.E))
{
if(!Input.GetKey(KeyCode.Q))
{
targetLeanAngle = -angle;
targetLeanDistance = distance;
}
}
else if(Input.GetKey(KeyCode.Q))
{
if(!Input.GetKey(KeyCode.E))
{
targetLeanAngle = angle;
targetLeanDistance = -distance;
}
}
else
{
targetLeanAngle = 0;
targetLeanDistance = 0;
}
}
else
{
targetLeanAngle = 0;
targetLeanDistance = 0;
}

float smoothAngle = Mathf.Lerp(cameraPosition.localRotation.eulerAngles.z, targetLeanAngle, leanDuration * Time.deltaTime);
float smoothDistance = Mathf.Lerp(cameraPosition.localPosition.x, targetLeanDistance, leanDuration * Time.deltaTime);

cameraPosition.localRotation = Quaternion.Euler(cameraPosition.localRotation.eulerAngles.x, cameraPosition.localRotation.eulerAngles.y, smoothAngle);
cameraPosition.localPosition = new Vector3(smoothDistance, cameraPosition.localPosition.y, cameraPosition.localPosition.z);```

willow scroll
tender stag
#

so when i hold Q

cosmic dagger
tender stag
#

i dont understand

#

what about this?

slender nymph
rocky canyon
#

i think it has to do with this

faint sluice
rocky canyon
#

or maybe the angle part

tender stag
#

its the angle

rocky canyon
#

its probably doing a full 360 to get to that

willow scroll
cosmic dagger
slender nymph
tender stag
buoyant knot
#

generally, if you go quaterion => euler => quaternion, you probably messed up

cosmic dagger
#

I haven't read the entire code but change it to the ruler angle z axis and test. It's a start . . .

cosmic dagger
tender stag
#

its the leaning thats not working

tender stag
willow scroll
tender stag
#

but its still doing a spin

#

dont look at the distance look at the angle calculations

cosmic dagger
#

What axis is it spinning on? Zero out that axis and test if it still spins . . .

slender nymph
faint sluice
tender stag
#

but when i lean to the right it starts spinning

rocky canyon
#

they both spin the same direction dont they?

tender stag
#

yeah

#

which they shouldnt

rocky canyon
#

yea i know... i know the issue.. just not how to fix it

tender stag
#

lmao

rocky canyon
#

its wanting to do a FULL rotation to get to ur negative angle

tender stag
#

yeah

rocky canyon
#

instead of rotating the opposite way of ur left lean

#

or right lean. (whichever ones working)

tender stag
#

left one is working

#

where you hold Q

rocky canyon
#

ill look around google a bit to try to find a solution for ya..

desert moon
tender stag
rocky canyon
#

may have to use some other type of rotation method

#

rather than setting it directly.. theres different methods u can call that will rotate thats not setting the rotation manually

willow scroll
#

That's why I've asked you whether it's possible to achieve this funtionality with IDraggable interface you were talking about

wet relic
#

hello everyone

slender nymph
rocky canyon
slender nymph
#

why you would want to be able to start dragging while hovering over some other object or nothing at all is beyond me though

faint sluice
#

Xy problem

rocky canyon
#

buttonPushed goes true when i click.. and then once ive passed a certain distance from where i originally clicked.. i do my logic

slender nymph
#

that isn't exactly what they are trying to achieve though. they want to be able to start dragging from anywhere within the green bounds in their image

rocky canyon
#

but yea.. i also raycast on buttonPushed.. to make sure theres a selectable under it

rocky canyon
#

maybe just a buffer area?

wet relic
#

hello everyone i am new to game making so i wonderd if someone wanna help me:)

timber tide
#

I only use the drag interfaces because you'd still have to poll in update otherwise even with the new update system

wet relic
timber tide
#

so I cant be bothered

slender nymph
cosmic dagger
#

@willow scroll I do agree, it is weird to click outside of an image and still drag it. What if they attempt to click/select a different image that is within the invisible threshold?

tender stag
#

this is how

rocky canyon
#

what did u use?

willow scroll
slender nymph
#

huh?

tender stag
#

and also as the first thing

#

i passed themselves into the lerp

reef totem
#

hey can anyon help me im a bit stupid and i forgot how to code

tender stag
slender nymph
faint sluice
rocky canyon
reef totem
#

but i have a specific question

tender stag
#

maybe in the future change it

willow scroll
rocky canyon
#

/tableflip just ask the fuggin question 😄

cosmic dagger
eternal falconBOT
#

:teacher: Unity Learn ↗

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

reef totem
reef totem
#

just give me one second

summer stump
#

!code

eternal falconBOT
willow scroll
rocky canyon
#

im not.. its just methods and if conditionals running in update

#

i use distance tho... it doesnt matter which direction..

willow scroll
rocky canyon
#

its a radius from the selectable i click on

rocky canyon
willow scroll
rocky canyon
#

yea i realized after box clarified

willow scroll
#

That's why I was saying I didn't think it was achievable with IDraggable

rocky canyon
#

may have to roll ur own solution.. i've never used IDraggable.. i need to tho just so i kno what its all about

reef totem
#

sorry if im being confusing you guys i joined the server like 5 minutes ago but bassicly the problem that is being occured is that I have been wanting to make a level selector for my levels and im using buttons for that. and I put all my button funtions in a seperate class the only issue being that i cant access the functions froms my class

slender nymph
reef totem
#

I can show you the code if you want me to

willow scroll
rocky canyon
# reef totem yes

another thing.. that script w/ all the functions has to be on a gameobject in teh scene..

#

u drag that gameobject into ur button and then find the method

slender nymph
polar acorn
rocky canyon
# reef totem it is

can u show the inspector of one of ur buttons? with this gameobject u say u have in the slot?

reef totem
#

shure

willow scroll
reef totem
slender nymph
polar acorn
faint sluice
# reef totem

You have created a Monobehaviour script inside another script

reef totem
faint sluice
#

Take that out and make it a seperate cs file

polar acorn
#

(that you can never actually use)

reef totem
#

why not

buoyant knot
#

you can only get a recttransform size in world coords in 2D in overlay view IF it is a sidescroller, and even then that information doesn’t always play nice

summer stump
polar acorn
#

You physically cannot add this component to an object

#

Meaning it's impossible you've dragged in an object with this component on it

buoyant knot
#

like you’d have to treat menus the same with the same methods as if you did not have the 2D camera overlay to relate screen-world space

reef totem
reef totem
#

ok then what are some possible solutions

polar acorn
summer stump
#

Just put it in its own file 🤷‍♂️
Super easy

buoyant knot
#

make a separate file

polar acorn
reef totem
#

yea ig but then it will be a bit less unorganised

polar acorn
#

Why is this in the same script anyway

rocky canyon
#

more organized*

summer stump
rocky canyon
#

lmao

reef totem
polar acorn
#

For that matter, why is this another class at all

polar acorn
reef totem
buoyant knot
#

putting more shit into one file makes it less organized

rocky canyon
#

tucking stuff inside other stuff is almost the definition of unorganized

#

lol

summer stump
buoyant knot
#

you want more separate files with simple classes

rocky canyon
#

SOLID!

polar acorn
#

You've thrown the laundry into the kitchen cupboard and called it organized. Just because you can't see it doesn't mean it's not still a mess

reef totem
#

na because the way I see it is that my game very small so I just want to have the least amount of scripts as possible so I dont have to switch between them

cosmic dagger
buoyant knot
#

i only combine classes into one file if one class is like <50 Lines of code, and if it makes a lot of sense to combine them

summer stump
reef totem
#

but if thats makes it unirganised then ig I have a lot of organisation to do

polar acorn
rocky canyon
polar acorn
#

Literally why not just put the functions in the class you want them to be in

rocky canyon
#

single responsibility

rocky canyon
#

np mate 🍀

buoyant knot
lost anvil
#

looked everywhere for a tutorial on how to create a super simple inventory system for my game, couldnt find anything. hoping someone can give me some pointers?
ive already got a system to add and remove objects into an array too.

code - https://gdl.space/otusuhoxiy.cs

polar acorn
cosmic dagger
lost anvil
#

yeah i dont mean like that

#

i mean just a scroll wheel one

#

by simple i mean basic

buoyant knot
#

unity links a file to at most one monobehaviour or scriptable object. If you want to drag and drop it around and keep it on a gameobject or asset file, they must be separate files.
Period

unreal imp
buoyant knot
#

!code

eternal falconBOT
unreal imp
#

srry

faint sluice
buoyant knot
#

i’m on mobile, and that code is literally 3 screens of scrolling

cosmic dagger
unreal imp
faint sluice
unreal imp
#

i made that to make a clearer animation transition

willow scroll
# summer stump You cannot. That is the answer

No, you can get the rect's size in world coordinates it by calculating the difference between object's corners.

public Vector2 GetWorldSize(RectTransform rect)
{
    Vector3[] panelCorners = new Vector3[4];
    rect.GetWorldCorners(panelCorners);

    return (panelCorners[2] - panelCorners[0]) / 2f;
}
slender nymph
#

why does any of that need to be converted to world space for that?

summer stump
#

This is absolutely wild

slender nymph
#

or has this whole issue been because your "threshold" distance is in world space units for some reason

willow scroll
#

Exactly, I have explained how it's affected by pivot

reef totem
#

Hi im back after like 5 minutes because my code does not work again and yes now I have made a new script for loading all me levels is it okay if any of you guys help me. I will send a picture of my code right now

slender nymph
reef totem
buoyant knot
willow scroll
reef totem
willow scroll
#

The pivot cannot affect anything in world space. It affects just local space.

slender nymph
faint sluice
# reef totem

Give reference of the object that's holding levelselector script on your button

summer stump
slender nymph
slender nymph
#

so this whole fucking issue has just been you misrepresenting what you are trying to do, willfilly ignoring what literally everyone has told you, then expecting anyone to understand with vague explanations that are just using incorrect terminology that further confuses the point

buoyant knot
#

world space = distance in meters.
screen space = distance in pixel.
canvas space = distance in resolution-invariant pixels

faint sluice
willow scroll
faint sluice
summer stump
reef totem
willow scroll
faint sluice
willow scroll
#

See, your localPosition is calculated from your pivot

reef totem
willow scroll
#

So it's gonna be the middle of the object if your pivot is (.5, .5) and its bottom left corner if its (0, 0), which required you calculating the offset to receive the real middle of the object

faint sluice
# reef totem

This doesn't have levelselector on it, you lied to me :v

reef totem
#

its on a panel and also forget about the other script its irrelevenet

faint sluice
reef totem
#

called

buoyant knot
#

you understand that worldspace is in 3D, and canvas space is 2D?

faint sluice
#

I just wanna see there's an object with "levelselector" on it

reef totem
#

I just changed the name of the class

faint sluice
#

Ohh

buoyant knot
#

and going between world and canvas space requires additional information that you do not have in that function

faint sluice
# reef totem

You have to change the name of the class from inside too

Filename and classname should be same

reef totem
#

so i need to make the name level selector

#

or scene levels

faint sluice
#

No, just change the name of that class to SceneLevels now i guess

#

Or change the file name to LevelSelector

#

Whatever you like

#

Either is fine

buoyant knot
#

pivot is neither in screen space, world space, or canvas space. Pivot is dimensionless

polar acorn
reef totem
buoyant knot
#

which only matters if you have multiple classes in the file

#

otherwise unity can figure out “it’s the only one there”

polar acorn
#

Going forward, this will no longer be necessary, but as of the current LTS, it's still a requirement

buoyant knot
reef totem
buoyant knot
#

you should adjust the file names to match regardless

polar acorn
faint sluice
slender nymph
#

i thought the change was made in like 2022.2 so the filename requirement should be gone in the latest lts

buoyant knot
#

eitherway, we can agree that it is bad form to have GrandmaScript.cs contain GrandpaBehaviour : MonoBehaviour

polar acorn
faint sluice
buoyant knot
#

i’m pretty sure I have gotten away with changing my monobehaviour class name, without updating the filename

faint sluice
cosmic dagger
#

that's going to cause so much headache when everyone starts using it . . .

faint sluice
#

Ain't no way this becomes mainstream right?

polar acorn
buoyant knot
buoyant knot
faint sluice
buoyant knot
#

so you should only find out if you fuck up

buoyant knot
slender nymph
polar acorn
#

Yeah, it's still a good idea to make the names match anyway

faint sluice
#

Ohh

polar acorn
cosmic dagger
polar acorn
#

I was in the process of installing 2022.2 to check, I didn't think of looking at the dev blitz days archive

slender nymph
#

that's where i'd first read about that change and I don't have any 2022 versions installed so I figured i could probably find the answer in there again

slender nymph
young lava
#

Hi, short simple question. Does StopAllCoroutine stop all the coroutines in a script instance, or all coroutines on the gameobject the script is on?

slender nymph
#

it stops all the coroutines owned by that MonoBehaviour

cosmic dagger
#

@young lava

buoyant knot
#

i never actually use that method

cosmic dagger
#

me neither . . .

buoyant knot
#

I almost exclusively keep a reference to the specific Coroutine, and turn it off manually

#

because I usually need to be able to know if the coroutine is running or not, to avoid running duplicates

young lava
#

I am probably going to do that tbh

cosmic dagger
#

it's much easier to track when you have a reference to it . . .

buoyant knot
#

usually:
private Coroutine despawning;

if (despawning != null) StopCoroutine(despawning);
despawning = StartCoroutine(Despawn());

Despawn coroutine sets despawning = null at very end

#

or
if (despawning == null) despawning = StartCoroutine(Despawn());

#

otherwise you have no clue wtf is going on, and can start duplicates of the coroutine, or not start it etc

#

and every time you call StopCoroutine, you set it null

#

so it effectively tells you if it is running or not

young lava
#

The problem I am having is I have state/action manager script. In that script I have a coroutine that pretty much tells how long a particular action should be locked for after performing an action. And I am running StopAllCoroutines in another script and it seems to be effecting the coroutine in my state/action script. I have some debug statements that are printing the actionLock booleans and as soon as I execute the StopAllCoroutines, the boolean remains toggled on which leads me to think that it is somehow stopping the coroutine in my other script. I will attach my code below.

#

State/Action Coroutines:

buoyant knot
#

for reference, my project has 38 calls for StartCoroutine, and zero StopAllCoroutines

#

don’t have a different script manage your coroutines

#

other script can call a method, and this class can manage its own coroutines

young lava
#

Code in charge of stopping coroutines. When I switch to the commented out code it works fine.

buoyant knot
#

ok, do the pattern I showed above

young lava
#

kk

slender nymph
buoyant knot
#

you’re right. Ienumerator should be green

#

!ide

eternal falconBOT
young lava
#

but lowkey I might still switch to manual like loup said thats better practice right?

slender nymph
#

yeah, it's probably going to work better to explicity stop the ones you want rather than using StopAll. but also how are you starting the coroutines? because if your StateMachine class is the one starting the coroutine then that is the one that owns that instance of the coroutine so that coroutine will stop when StopAllCoroutines is called on that MonoBehaviour

young lava
#

So pretty much I am calling stateMachine.SetAttackActionLockForDuration(randomNumber) in another monobehavior. specifically my script in charge of handling melee attacks. And the StopAll is being called in the same melee attack class which is the confusing part.

buoyant knot
slender nymph
young lava
#

Sorry I meant StartCoroutine()

slender nymph
young lava
#

Ohhh so even if the coroutine logic itself is located in playerController, since I am running StartCoroutine in the WeaponController script, if I call StopCoroutine in the weapon controller it will stop the "playerController" coroutine?

slender nymph
#

correct because that MonoBehaviour instance is what is running that instance of the coroutine

buoyant knot
#

StopCoroutine lets you pick which coroutine specifically you want to stop

young lava
#

Thank you guys!

buoyant knot
#

StopAllCoroutines applies to all coroutines on that one instance of that one class

young lava
#

Yep definitely going to switch to full manual control!

slender nymph
vapid void
#

I just started unity and this line of code gives me an error: if (LeftAction.isPressed())

buoyant knot
#

you won’t need the action locked bool either anymore

cosmic dagger
#

that code tells us nothing by itself . . .

vapid void
flint rock
#
 private void OnCollisionEnter(Collision collision)
 {
  

     GameObject enemyObject = collision.gameObject;
   //  UnitCombat unitStats = enemyObject.GetComponent<UnitCombat>();
     bool disableDamage = false;
     print(gameObject);
     GameObject rootObject = gameObject.transform.parent.gameObject;
     rootObject.GetComponent<UnitBehaviour>().getUnitType();

  /*   if (health <= 0)
     {
         Debug.LogWarning(gameObject + "OBJECT DEAD");
         disableDamage = true;
     }
     
     if (_unitType == UnitBehaviour.unitTypes.Dummy)
     {
         print("OW! Took " + unitStats.damage + " damage from " + enemyObject);
     }
     else if (_unitType == UnitBehaviour.unitTypes.Melee)
     {
         print("Applying damage");
         unitStats.health -= damage;
         print("Applied damage: " + damage);
         
     }*/


 }

Why is this printing the name of the collision object, instead of the object that is the parent of this script? It should be printing the name of the object that is the parent of this script, pretty sure that's gameObject functionality. I can't decide if this is a glitch, or if for some reason Unity made the functionality of gameObject different inside of OnCollisionEnter vs outside of OnCollisionEnter, or I've made a very obvious oversight

slender nymph
cosmic dagger
# vapid void

it's telling you that the isPressed method does not exist for the type InputAction. also, you should have a red squiggly error line in your !ide. if not, make sure to configure it . . .

eternal falconBOT
desert moon
#

Ok, recording this with recorder, the jitter is even worse than it was before. I've decoupled the camera object from the camera rig and tried to have it match an object's pos/rot. But there's a jitter. The player offsets a consistent distance. I have a feeling it could be because the camera might be a frame behind.

#

Anyone encounter something like this?

slender nymph
#

yeah this is likely due to updating the camera at a different rate or before the object during the frame

desert moon
#

Could it be because the character is using a rigidbody to move?

slender nymph
#

possibly. you've not shown any info about how you update the camera's position or at what rate/part of the frame

buoyant knot
# young lava whys that?

because if the coroutine sets its own Coroutine to null, then you know if it is running or not based on whether that variable is null

desert moon
#
public class ActorCamera : MonoBehaviour {

    public ActorBase user;

    public void LateUpdate ()   {

        transform.position = user.transform.position;
        transform.eulerAngles = new Vector3(user.lookAngle.x,user.transform.eulerAngles.y,0);
        MainCamera.singleton.UpdatePos();

    }


}```
Here's the script that operates the Camera Rig.
desert moon
#
public class MainCamera : MonoBehaviour
{
    public static MainCamera singleton;
    public Transform targetObject;
    Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        MainCamera.singleton = this;
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    public void UpdatePos()
    {
      rb.position = targetObject.position;
      rb.rotation = targetObject.rotation;   
    }
}

And the main camera itself.

#

I have a hunch. Maybe I need to add a rigidbody to the camera rig too and have the rig script operate that instead.

slender nymph
#

oh god no, don't do that

#

my suggestion would be to use Cinemachine

#

and you probably want interpolation enabled on the rigidbody if it isn't already

desert moon
#

On the player rigidbody?

#

Is it bad that I'm plugging in the movement values to the rigidbody velocity directly?

unreal imp
# faint sluice First off, horrible way to start coroutines...should avoid starting coroutines i...

Sorry for responding late but then how do I apply the UnFreezeAnimation to my code with the reload? In this example it works fine but it reloads instantly and I don't want that but for it to run an animation that plays after 0.25 seconds or so and then reloads when it runs, but if I apply it I get the usual error of consuming my bullets. ammo after reloading if (currentClipAmmo <= 0 && currentAmmo > 0) { Reload(); }

#

i was thinking like this but still with the same error public IEnumerator UnFreezeAnim() { isReloading = true; yield return new WaitForSeconds(0.5f); gunAnimator.speed = 1; yield return new WaitForSeconds(0.3f); Reload(); }

#

unfreeze animation is an anim which resume an animation state

#

when the ammo clip is below or same as 0 the animation plays

#

and get freeze until the ammo is more than 0

#

to that ammo the clip is refilled and then unfreeze the animation

#

now i applied the if (currentClipAmmo <= 0 && currentAmmo > 0) { StartCoroutine(UnFreezeAnim()); }

#

instead of the reload one

earnest forge
#

Does anyone have a solution to unsubscribe all interactions from an Action in the unity new input system?

wintry quarry
tender stag
#

how does one handle stairs and steps on a rigidbody movement system

#

i tried looking online but couldnt find anything

#

only videos about character controller

ripe shard
tender stag
#

might try that

#

and then calculating if the contact point is higher than x amount from the bottom of the player

ripe shard
#

whatever you do, in some way, you are converting the steps to a ramp

#

question is just which abstraction for that you use

desert moon
silk night
heavy current
#

can someon help me i dont now what this is

silk night
#

There may be some wonky physics Interactions but you will have to finetune any movement method eventually

desert moon
heavy current
#

what was that again ?

polar acorn
wicked stratus
#
    {
        if (beginFunction)
        {
            if (timeLeft > Time.deltaTime)
            {
                gameObject.GetComponent<SpriteRenderer>().color = Color.Lerp(gameObject.GetComponent<SpriteRenderer>().color, colorToChangeTo, Time.deltaTime / timeLeft );
                timeLeft -= Time.deltaTime;
            }
        }
    }

I have a sprite that I'm trying to transition smoothly from 255 opacity to 20 when the player triggers a collider, but I'm struggling on how to make it slowly change to that over say a second, rather than immediately. When I look it up, I see a lot of use of the Lerp function, and I think I kind of understand how it works conceptually, but in practice this isn't working. I've set timeleft to 1f. nothing is happening, though. im sure I'm missing something easy, but i could be wrong. can someone help?

polar acorn
heavy current
polar acorn
#

Second, Color uses values between 0-1, not 0-255. All opacity values over 1 are fully opaque

polar acorn
low path
#

Half the convos in this channel:
Q: I don’t understand this error message.
A: it literally tells you what to do. You assign a value to the reference.
Q: what’s a reference?
A: it’s a value that refers to an object in your game and can be assigned to a variable.
Q: what’s a variable?
A: it’s a thing in C# whose value can change at runtime.
Q: what’s C#?
A: it’s Unity’s scripting language.
Q: what’s that, I’m new.

wicked stratus
#

oh, right. thank you, I'm very rusty

heavy current
polar acorn
# heavy current yes

Okay, every other noun in that error message is something you made so if you know what an inspector is you should be fully capable of following what it's saying

heavy current
#

yes i just dont know what groundcheck is

polar acorn
polar acorn
#

It's a variable you put in your script

queen adder
#

i have a python script that fills a json file with data, how do i execute the python file and wait until the python file finishes the execution?

heavy current
polar acorn
polar acorn
wicked stratus
#

ok, I've cached the reference to the spriterenderer and changed the alpha values into floats between 0-1, but it's still not working.

    {
        if (beginFunction)
        {
            if (timeLeft > Time.deltaTime)
            {
                spriteRenderer.color = Color.Lerp(spriteRenderer.color, colorToChangeTo, Time.deltaTime / timeLeft );
                timeLeft -= Time.deltaTime;
            }
        }
    }

Is the issue with the timeleft being 1? I don't know why it's set like that, but it seemed to be a common trend.

queen adder
heavy current
#

public class player : MonoBehaviour
{
public float speed = 5;
private Rigidbody rb;
public float jumph = 5;

// Start is called before the first frame update
void Start()
{
    Rigidbody2D rigidbody2D1 = GetComponent<Rigidbody2D>();
    
}

// Update is called once per frame
void Update()
{
    float richtung = Input.GetAxis("Horizontal");
    transform.Translate(Vector2.right * speed * richtung * Time.deltaTime);

    if(Input.GetKeyDown(KeyCode.Space))

    {
        rb.AddForce(Vector2.up * jumph, (ForceMode) ForceMode2D.Impulse);
    }
}

}

#

no groundcheck

queen adder
#

i can easily run the file

polar acorn
#

I asked for PlayerController

rocky canyon
#

thats not PlayerController script anyway

polar acorn
#

Also, !code

eternal falconBOT
heavy current
#

im so confused

polar acorn
rocky canyon
#

those are different scripts..

polar acorn
rocky canyon
#

u have a script in ur project somewhere called PlayerController

#

u showed us player

queen adder
polar acorn
rocky canyon
#

wait a minute.. so i can run python scripts now using my unity editor 👀

low path
polar acorn
heavy current
#

Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.transform.position, 0.2f);
isGrounded = colliders.Length > 1;
}

polar acorn
#

Don't think you can run it in-game

heavy current
#

this ?

polar acorn
#

But where are you setting it

rocky canyon
elder osprey
#

I don't understand what I am doing wrong in this script, I am trying to apply a custom acceleration speed to the player with a rigidbody, but currently the player isnt moving at all. Here is my movement code: ```cs
void FixedUpdate()
{
Move();
}
void Move()
{
Vector3 velocity = rb.velocity;
Vector3 desiredVelocity = new Vector3(moveInput.x, 0, moveInput.y) * speed;
float maxSpeedChange = maxAcceleration * Time.fixedDeltaTime;
velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange);
velocity.z = Mathf.MoveTowards(velocity.z, desiredVelocity.z, maxSpeedChange);

rb.velocity = transform.TransformDirection(velocity * Time.fixedDeltaTime);

}```

polar acorn
heavy current
#

CheckGround(); this?

wicked stratus
polar acorn
wicked stratus
#

is something like this colorToChangeTo = new Color(spriteRenderer.color.r, spriteRenderer.color.g, spriteRenderer.color.b, 0.02f) valid code?

polar acorn
wicked stratus
#

let me see, it ought to

rocky canyon
#

very interesting code tbh

wicked stratus
#

yes

rocky canyon
#

at my state of knowledge id have to take time to debug that to even know how it functions

#

ur subtracting the time between frames from timeleft.. until timeleft is less than the time between frames?

wicked stratus
#
    {
        if (beginFunction)
        {
            Debug.Log("1");
            if (timeLeft > Time.deltaTime)
            {
                Debug.Log("2");
                spriteRenderer.color = Color.Lerp(spriteRenderer.color, colorToChangeTo, Time.deltaTime / timeLeft );
                timeLeft -= Time.deltaTime;
            }
        }
    }

both log statements are hit

rocky canyon
#

🤔

elder osprey
rocky canyon
#

do ur inputs work?

wicked stratus
rocky canyon
#

yea thats what it looks like.. but logically.. i dont know how thats useful

#

lol

polar acorn
wicked stratus
#

one moment

rocky canyon
#

ohh its just a basic percentage counter

polar acorn
#

That would explain why it's not moving

elder osprey
rocky canyon
#

are ur inputs working correctly?

#

b/c if not.. ur desiredVel is gonna be 0

elder osprey
#

Yes, I just checked

rocky canyon
#

ok thats the only thing i got sorry

wicked stratus
#

looks like it stops at .68 for some reason

#

the alpha component hasn't changed at all, though

#

Should i be using color32

spring coral
#

i have a script attached to a prefab and this script has an id associated with it, if i grab the script/id (as the prefab reference itself, not the instantiated prefab) will it cause any problems?

#

im not manipulating the prefab, just need to read some data from it

wicked stratus
#

wait, when I trigger it again, it stopps at .93

#

either way the opacity is not changing.

rocky canyon
#

but u know my skill - level so take that as u will

spring coral
#

was scared some things might not get initialized or something but makes sense there wouldnt be a problem tbh

#

just had to double confirm, thanks!

wicked stratus
#

Is this even the right approach to try to change a spriterenderer's opacity smoothly

rocky canyon
wicked stratus
#

im sure there's gotta be an easier way

spring coral
#

yeah treating it as a read-only source as a prefab

rocky canyon
#

its easier for me to visualize

#

im familiar with 0-255 not so much 0-1

#

if (timeLeft > 0) what happens if u use this conditional instead.. so it'll lerp until time is fully exhausted

#

instead of stopping once its lower than the framerate

wicked stratus
#

let me try that. I'm going to switch to color32 since it works better in my brain too

rocky canyon
#

👍 make those two changes and see if some magic doesnt happen lol

elder osprey
rocky canyon
#

wait. im not sure if u can use Color.Lerp for Color32s

elder osprey
#

So increasing the acceleration fixed it.

rocky canyon
#

😈 lol

wicked stratus
rocky canyon
#

nice! good job

wicked stratus
#

ah wait- it doesn't reach the desired amount at the end of the timer, but i need that to happen

rocky canyon
#

even with the > 0 conditional?

polar acorn
#

you have to do that manually

wicked stratus
#

ah ok I see, thank you

rocky canyon
#

& ohh thats true..

timber comet
#

anyone that knows how to check for "any key" pressed with the new input system? (from any type of device)

rocky canyon
#
 if (Keyboard.current.anyKey.isPressed)
        {

        }```
#

lol.. nah not really

#

ahh u ninja edited, now my joke doesnt work

wicked stratus
polar acorn
#

As that number approaches 1, your color approaches the target

wicked stratus
#

I'll try some floats it is still clear i am not sure how to handle the last bit

rocky canyon
timber comet
rocky canyon
#

ya, i didnt see hardly anything from my different few google searches sorry

wicked stratus
#

oh! got it

#

awesome

#

thank you both

rocky canyon
#

has to be possible tho.. b/c thats the purpose of the new input system.. scaleability

timber comet
rocky canyon
#

yo, why wouldnt that work?

#

if u have all ur different inputs under different action maps u can just run multiple of those conditionals.. checking all the action maps u have set up

#
    {
       //doo thang
    }else if (inputActions.actionMap.GamepadScheme.WasPressedThisFrame())
    {
       //doo thang
    }else if (inputActions.actionMap.TouchpadScheme.WasPressedThisFrame())
    {
       //doo thang
    } ```
#

idk, i promised i'd start using it and i havent yet :d

timber comet
rocky canyon
#

i like the old too, but so far ive only made keyboard input games

#

kinda a restriction at this point in time

timber comet
elder osprey
#

I am experiencing an issue, the accelerationMultiplier is changing the entire speed instead of how fast the player accelerates in the desired direction, so lowering the accelerationMultiplier is just lowering the speed. Here is my movement code currently: ```cs
void FixedUpdate()
{
Move();
}
void Move()
{
Vector3 velocity = rb.velocity;
Vector3 desiredVelocity = new Vector3(moveInput.x, 0, moveInput.y) * speed;
float maxSpeedChange = speed * accelerationMultiplier;
velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange);
velocity.z = Mathf.MoveTowards(velocity.z, desiredVelocity.z, maxSpeedChange);

rb.velocity = transform.TransformDirection(velocity * Time.fixedDeltaTime);

}```

rocky canyon
#

😄 i can already picture it

#

lol

#

you need to calculate ur aceleration seperately

#

and then add it to the velocity

rocky canyon
#

but then ur gonna need to clamp ur velocity afterwards so it doesnt exceeed ur maxSpeed

pallid nymph
#

acceleration should be a vector and be clamped properly... with this code you'll accelerate faster if you move diagonally, no? (or maybe I'm just sleepy)

rocky canyon
#

the ole.. normalization?

#

is that not a side- product of TransformDirection? probably not lol

pallid nymph
#

why you need to do transform direction I'm also not sure...

#

I can come up with an explanation but... code very borked and not quite sensible (sorry)

rocky canyon
#

iono, maybe he came across the issue where his velocity/direction is locked to world space

#

when he wants it local space (we cant see his rotation code)

elder osprey
#

This is my rotation code cs Vector3 projectedCamForward = Vector3.ProjectOnPlane(Camera.main.transform.forward, Vector3.up); transform.rotation = Quaternion.LookRotation(projectedCamForward);

rocky canyon
#

ya, i guessed b/c thats the only time i ever use it 😄

pallid nymph
#

so... you need to TrnsformDirection the input... then convert it to acceleration (multiply by acceleration mp and deltaTime I guess)... then add to rb.velocity... and then clamp the rb velocity

rocky canyon
#

i think this would work

pallid nymph
#

it will accelerate faster diagonally

rocky canyon
#

ohh yea i ignored that completely

#

but so did he 😄

pallid nymph
#

maybe it's a feature! 😛

rocky canyon
#

maybe he does it in input thinksmart

elder osprey
rocky canyon
#

unless u normalize ur vectors ur gonna travel faster diagonally than u do forward or lateral

elder osprey
#

I'm using the new input system

#

So the input is already normalized

pallid nymph
#

that doesn't matter

rocky canyon
elder osprey
#

But I am experiencing another problem

elder osprey
rocky canyon
#

i made a graph as to why the normalization is needed

#

u can see right is 1, up is 1.. but if u add them.. ur at (c)

#

which is longer than the other two..

#

normalizing puts it at the orange dot... so every direction is equal

rocky canyon
crystal cipher
#

what should i do

elder osprey
eternal falconBOT
rocky canyon
#

translation doesn't respect physics

#

its basically teleporting.. so theres times when it'll teleport too far on a given frame.. and clip into walls and stuff.. (then it just gets yeeted out the other side)

crystal cipher
#

ok

#

some how else i can move it?

rocky canyon
#

if u want accurate physics.. u need to use a rigidbody to move it

#

and rigidbody functions..

pallid nymph
#

and be prepared to be spending a lot of time on it

rocky canyon
#

or if its a simple enough game.. u can set up boundaries. (like if its position is less than this X) allow it to move..

rocky canyon
#

if its over that position only let it move the opposite direction.. (but thats gets nasty)

rocky canyon
# crystal cipher how?

its pretty involved, id suggest u look up a tutorial on how to move rigidbody's in unity

#

you can use functions like rigidbodyReference.AddForce() but the way ur already calculating speeds and stuff u could manualy set the velocity of a rigidbody..
rigidbodyReference.velocity =

#

just would require a bit of tweaking to ur setup to add the components u need

#

boom rigidbody 101

thin hollow
#

Hi, i have a string that has a public getter but private setter. how do i actually set it lol?

public string mainAbilityName { get; private set; }

#

mainAbilityName = "Name";
that dont work lol

slender nymph
#

that absolutely would work inside a method in that class

summer stump
thin hollow
#

so it needs to be in a method?

slender nymph
#

you cannot just have random statements floating around in the class

thin hollow
#

what if i dont want it to be in a method, but i still want it to be privatly set, publicly get

slender nymph
#

you can initialize it with a value by appending the assignment to the end of the declaration like public string Name { get; private set; } = "Name";

thin hollow
#

ah ok thats it

#

thank you!

slender nymph
#

otherwise you have to assign it in a method

#

also note that will not work for properties declared in structs

thin hollow
#

btw how to u do that code tag in discord

slender nymph
#

!code

eternal falconBOT
cedar crest
#

Hello! Is it possible to bake lighting during runtime? If I have a map generated randomly and it never changes, bake the lights before the game starts?

hot wave
#

I have been experimenting with brackeys 3d character controller, and it doesnt have drag and momentum, I kind of want to code it using character controller because I want to avoid problems involving rigid bodies, would that be possible? but everytime i try to add velocity or easing speed, it doesnt apply it, as if it is only moving the vector 3 of the object and moving it around the map, and no physics thingy

#

it is using a quaternion thingy, but i dont know how to hook that or integrate it so i could make easing speed up or speed down on keydown or keyup

#

It is like I know how the code should look like (but i could still be wrong) but I cant put it into code UnityChanThink

frosty hound
#

The CC requires you to pass in a velocity for the frame. How you calculate that velocity is entirely up to you.

#

You can do whatever you want, speed it up, slow it down, change directions.

hot wave
#

would easing speed up and down also work? if i stopped pressing w, it would slide easingly after

frosty hound
#

You can do whatever you want

hot wave
#

could you give me a hint on how it could work, I want to figure it out on myself as well, I am confused, but I have a feeling Mouse look has influence over the movement in character controller? where should I look in the code to start adding easing speed up and down?

#

if ok UnityChanOkay

frosty hound
#

It's a complex and big topic.

#

You need to have a strong understanding of vectors

hot wave
#

okok, also, this was in mouse look, is it ok to copy the code and add it in character controller? it is a diff script, or can i import it easily?

frosty hound
#

Again, you can do whatever you want

#

Unfortunately that means you can do whatever you want

hot wave
#

I will try, thank you steel

supple citrus
#

How do Displays work? Im currently using a camera to focus on a small region of the screen and put it on display 2. I don't actually want the user to see this display, Im just using it to take screen captures. Im not fully sure I understand how it works, Im reading that someone with multiple monitors would be able to see it, is this right?

slender nymph
#

just render the camera to a render texture instead of a display

supple citrus
#

If I set a render texture will it not go to a display?

#

Sicne there isnt a none option

manic geyser
#

how do i know if a number between -1 to 1 is closer to -1 or 1?

oblique ginkgo
#

if n > 0 its closer to 1 if n < 0 then its closer to -1
if n == 0 its neither

manic geyser
#

okay but

#

this worked before when i did .GetAxis, but now i have the raw input from a joystick instead

oblique ginkgo
#

raw input from joystick is likely analog float, so youll get like 0.93564
getaxis is digital, 1 or -1 or 0

manic geyser
#

i guess roundtoint would be best then

#

to best replicate GetAxis

oblique ginkgo
#

what if the joystick is less than half pressed to a direction

#

then it rounds to 0

manic geyser
#

yes that is why i'd rather have it always return -1 or 1 when theres an input

oblique ginkgo
#

so then check if its above or below 0

#

above 0 means 1
below 0 means -1

#

and if its 0 then theres no input

manic geyser
#

i feel like there probably is some math function to do all this inside the if statement. maybe

#

but this pretty much does it

oblique ginkgo
#

you dont need the roundtoint there

manic geyser
#

oh forgot that one

oblique ginkgo
#

also, x can be an int

#

instead of float

slender nymph
#

just use Mathf.Sign

oblique ginkgo
#

that.. also works

slender nymph
#

you'd have to check for 0 though since unity's Mathf.Sign returns 1 for 0

real falcon
#

I'm having difficulty with movement code again, I still can't get it perfect

#

it has this weird property where what I think is happening is, when you turn you slow down

#

and so then when you stop turning, you immediately go back to full speed

#

which FEELS glitchy

#

I thought it was like framerate weirdness for the longest time

#

but I think it's because when I turn, it adds some new velocity in a different direction, rather than like "turning" the vector idk

#

the code I have right now is pretty simple in theory, it takes player input and adds a vector to the player's velocity based on that, then adds a friction vector that's opposite to the current velocity

supple citrus
#

Can we see it

real falcon
#

the code?

supple citrus
#

Yeah

#

If its slowing down then I'd guess something in the friction vector is doing it

#

but I cant say until I see

real falcon
#

// The desired velocity (input with length of acceleration)
Vector3 wishVec = inputVector * groundAcceleration * moveForce;

// Draw velocity
Debug.DrawRay(transform.position, playerVelocity * 2, Color.yellow);

// Friction factor modifies friction based on stuff like sliding
//float additionalFriction = playerVelocity.magnitude / 10f;
additionalFriction = 0f;

playerVelocity += wishVec * 0.01f;
        
// Friction
Vector3 fric;
fric = playerVelocity * (friction + additionalFriction);
     
playerVelocity += fric * 0.01f;

controller.Move(playerVelocity * Time.deltaTime);```
#

this is basically the whole thing minus the mouse code and jumping

#

inputVector is just WASD but it's localized to where the player is looking

supple citrus
#

If you were holding two keys at the same time, would there be 2x the velocity which would lead to a higher friction?

#

I don't know how youve gotten your 0.01 multiplier when adding the friction, but maybe theres a point at which the friction increases faster than the velocity so you actually have a higher resistive motion (friction) when you go faster (turning)

real falcon
#

I don't think the keys add together, I normalize the input vector

#

as for the 0.01 I think my project is weirdy small or something

#

the smallest increment I can move things with the gizmo arrows seems a bit big idk

supple citrus
#

Probably a Screen vs World issue

real falcon
#

im not sure why the friction would go faster since it's just a proportion of the velocity

#

also this seems to happen specifically when im holding W and one of the strafe keys

#

and then turning the mouse to do kind of a sharp turn

#

I actually tried it in DUSK and surprisingly it seems to work like that there too, but it's less jarring there and I'm not sure why

supple citrus
#

So when you don't move the mouse, it doesn't slow down?

real falcon
#

I mean it does in the sense that im changing direction

#

I wonder if it's less noticible in DUSK because its acceleration is a bit slower

#

I mean it makes sense intuitively

#

I'm turning into a new vector that's not pointing in the same direction as the old, of course it's gonna slow down a bit

#

im just not sure why the acceleration once I stop moving the mouse feels so harsh

grizzled zealot
#

What is better for performance on a space game:

  1. Create a gigantic repeatedly tiled sprite background
  2. Constantly compute the offset and have the sprite move with the player
#

(2D space game)

cinder crag
#

can someone help me fix the text cause it looks very weird and im not sure how to fix it brbrbr

vale karma
#

is there a 'getkeydown' feature for the new input system? im having trouble finding the right implementation for only allowing a single jump, and pressing the escape key for a pause menu

sterile moon
#

This is a script I found online for a realisitic car controller, I've been reading through it to understand how it all works, but, I can't figure out how the hell its getting input from the keyboard to know what to make the car do. They did say they use the old input system, but I'm unsure what that is or what to look for in that case

https://hastebin.com/share/liligidejo.csharp

sterile moon
vale karma
#

thats old news

sterile moon
#

Ah, interesting, what the hell is the new system then

slender nymph
#

whatever is getting input is in a different class

queen adder
#

this is a really new question but how would i connect a scene to another scene?
like if i wanted a player in a certain area of a attack to go to a seperate scene
would i just trigger a scene if player in area?
srry english not very good

sterile moon
# slender nymph whatever is getting input is in a different class

The entire download to this is linked in the description of this video, I have looked over all his code and can't seem to find it. I'd love some help, as I'm wanting to play with the settings to see how I can improve the handling.

https://www.youtube.com/watch?v=WjT1acvP9pc&t=7s

Free Car Controller / Vehicle Physics Project for Unity With Vehicle Damage.


Mobile Coming Soon.....


A free car controller fo...

▶ Play video
vale karma
#

i tried using waspressedthisframe but that only changes a bool to true once and keeps it like htat. i need something that checks every frame if the esc key (or whatever input is routed there) to pop up a pause menu, and press again to close. Atm my code only reads the value as a button, so if i hold the button down, or not tap super quick, the UI flashes off and on really fast

slender nymph
#

yeah i'm not downloading that

slender nymph
vale karma
#

can you do the ! code thingy? paste.ofcode has error 1033 on it

sterile moon
#

!cide

#

!code

eternal falconBOT
slender nymph
vale karma
#

ohh lol its just cod ehahaha

cinder crag
vale karma
#

what was that one i could do tabs with

slender nymph
vale karma
slender nymph
vale karma
#

in other words you should think outside the box, friend ;D

cinder crag
slender nymph
vale karma
#

it references the statemachine script

vale karma
#

im probably not gonna change that part bc its too much to change lol. i understand it so far and dont want to screw up the toothpicks holding up this establishment haha

cinder crag
#

its just a TextMeshPRoUGUI

vale karma
slender nymph
vale karma
#

you could do two if statements consisting of if magnitude reaches a certain threshold it will display this text, and then vise versa for the other speed @cinder crag

slender nymph
#

most likely they have two variables that they just want to choose from. of course they decided to only show that single line instead of all of the relevant code

vale karma
#

or you could... build a statemachine ;3 wink wink

queen adder
#

Whats up J-bear?

vale karma
#

if (Keyboard.current.escapeKey.wasPressedThisFrame) <- this is a workaround. Id rather the keybinds be 'bindable' by the player later on in the game. but this is okay for now since i only need one or two

queen adder
#

I see you typing BOY

vale karma
#

hiya

#

i ate a 1g distillate edible i made, waitin to see if it works lol

queen adder
#

Keybdings be bindable? Do you mean its supposed to be able to change to a different key later in the game?

vale karma
#

yes

queen adder
#

I mean being able to change what keys trigger the actions should be its own class

#

So ur other scripts shouldnt really care what key is being pressed. They should only key care about the Input Action itself being raised / Triggered

#

I remember you saying as well that ur jump wasnt working. Were you able to figure it out?

arctic ibex
#

Quick question, what's going on here?

slender nymph
#

you need to yield return in a coroutine

arctic ibex
#

oh

#

okay

#

Why? Is that just how they work?

slender nymph
#

if you have no need to yield then you do not need a coroutine

arctic ibex
#

I guess that's fair enough

unreal imp
#

guys how i do for move the slide of the gun because i tried this but doesnt works slide.transform.position = new Vector3(slide.transform.position.x, slide.transform.position.y, slide.transform.position.z - 1);

teal viper
#

IEnumerator is a bit special in that instead of return, you need to yield return.

teal viper
#

Or slide is not the object you expect to move.

queen adder
#

how is this possible? And what is the solution

void OnCollisionEnter2D(Collision2D coll)
{
    currentdirection = Vector2.Reflect(rb.velocity, coll.contacts[0].normal);
}
sour fulcrum
#

I assume not but does anyone know if Physics.IgnoreCollision works on prefab assets when you instansiate them

teal viper
queen adder
#

oh havent thought of using the length

#

dunno what causing onEnter to not catch who touched it though

#

is this common?

teal viper
#

No. Doesn't sound normal

teal viper
queen adder
#

lemme see

teal viper
#

You need to allocate an array and pass it in.

summer cave
#

I dont understand what is wrong with this

 void Update()
    {
        if(Input.GetKeyDown(KeyCode.Mouse0))
        {
            FireRayCast();
        }
    }

    public void FireRayCast()
    {
           // Perform the raycast and store information about the hit
            
            if (Physics.Raycast(ray, hit.transform.position, raycastDistance, layerMask))
            {
                // Check if the hit object has a Rigidbody component
                Rigidbody rb = hit.collider.GetComponent<Rigidbody>();
                if (rb)
                {
                    // Calculate the force vector from the hit point to the object's center of mass
                    Vector3 forceDirection = rb.position - hit.point;
                    
                    // Apply the force to the Rigidbody
                    rb.AddForce(forceDirection.normalized * explosionForce, ForceMode.Impulse);
                }
            }

    }
faint sluice
summer cave
#

Should have pointed that out lol

if (Physics.Raycast(ray, hit.transform.position, raycastDistance, layerMask))

Also for 18 as well

FireRayCast();
slender nymph
#

what is hit and where do you assign it

faint sluice
#

Also i see we are good friends with GPT

summer cave
#

Hit is RaycastHit hit

summer cave
slender nymph
#

and where do you assign to it? because just declaring it does not give it valid RaycastHit with a non-null transform property

faint sluice
slender nymph
#

hint: you shouldn't be using hit at all for determining where the Raycast is at. you should be assigning it using the raycast

queen adder
slender nymph
summer cave
#

by assign do you mean what lines its being used on?

slender nymph
#

yeah fuck outta here with your AI generated code. it is against the rules to ask for help with AI generated code #📖┃code-of-conduct

summer cave
#

mb

slender nymph
queen adder
#

@teal viper im catching nres here(in the logs) and cant null-check, how to properly use it?

teal viper
queen adder
#

oh maybe just the othercoll is catching the nre

teal viper
#

To make it reliable, change that to a for loop and only iterate up to the returned length

teal viper
#

Really, you only need to debug the length of the contacts array

#

though, the fact that other collider is null might be giving some clues

#

If it's an uninitialized contact point, then obviously it wouldn't have a reference to the other collider

queen adder
#

there's some 0

teal viper
#

weird...🤔

queen adder
#

maybe because my skeletons have cheaper rbs?

#

then on the player is

unreal imp
# teal viper It should work. If you don't see any changes, then something else myst be resett...

in update: if (!outOfAmmo && currentClipAmmo <= 0 && currentAmmo > 0) { slide.transform.position = new Vector3(slide.transform.position.x, slide.transform.position.y, slide.transform.position.z - 1); StartCoroutine(MoveBackToOriginalPosition()); } the other method: ``` IEnumerator MoveBackToOriginalPosition()
{
yield return new WaitForSeconds(0.5f);
float elapsedTime = 0f;
float duration = 0.5f;

    Vector3 currentPos = slide.transform.localPosition;

    while (elapsedTime < duration)
    {
        slide.transform.localPosition = Vector3.Lerp(currentPos, originalPosition, elapsedTime / duration);
        elapsedTime += Time.deltaTime;
        yield return null;
    }
    slide.transform.localPosition = originalPosition;
    Reload();
}```
faint sluice
#

I don't think that matters, as that only checks how often collision should be checked, and oncollisionenter is called if it detected a collision only

teal viper
faint sluice
#

@queen adder just in case can you manually spawn 1 skeleton, and drag it with your mouse to collide with your player? See what gives the error?

queen adder
#

tried to make them similar, doesnt killed the 0 contacts

#

lemme try

teal viper
queen adder
#

but yea, i noticed it only occurs when the player is being swarmed

teal viper
#

Maybe it's just a bug that went under their radar for a long time..?

#

Might be worth filling a bug report.

queen adder
#

when many things push the object, the first thing that touched it lost reference

teal viper
#

Ah, but you're using a legacy version...

#

It could be fixed in the supported versions I guess

faint sluice
# queen adder

You are using 2017 editor might be older issue, maybe upgrade it to latest LTS versions?

unreal imp
foggy crypt
#

!code

eternal falconBOT
teal viper
faint sluice
foggy crypt
#

Hello
I want to make a code, that allows the player to press space if he stays in zone.
But for some reason trigger works only if I spam the Key, which is Space

I made an empty GameObject that refferences as the zone
And a Player with box collider and rigidbody

public void OnTriggerStay(Collider other)
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        pressSpace = true;
        StartCoroutine(spawnManager.SpawnBubbleFish());
    }
}

Sometimes when I launch the game it works properly
But sometimes it requires spam

faint sluice
#

Like
ontriggerenter inzone = true
Ontriggerexit inzone= false

In update
If(inzone)
{
If(onkeydown)
{
}
}

foggy crypt
foggy crypt
#

Yup, works perfect, just how I wanted it to.
Thank a lot

faint sluice
#

Hope you used ontriggerenter lol

unreal imp
teal viper
unreal imp
#

But not the translate xd

teal viper
abstract marlin
#

Im Curious why this Problem happens. Im Doing Unity Learn and im at Essentials of Real Time Audio.
Downloaded the Foundations of Audio Pack , did an URP 3D Template and imported it. Game Scene Looks Good.
So every time i press play i just fall through the ground .
Tried adding a cube as ground with Y at like -0.1 but still i flot through the ground... what am i doing wrong ?
All i literally did was Import -> Open and Press Play

uncut shard
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController: MonoBehaviour
{
private CharacterController controller;
private Vector3 direction;
public float forwardSpeed;
private int desiredLane = 1;//0: left 1:middle 2:right
public float laneDistance = 4;

public float jumpForce;
public float Gravity = -20;
void Start()
{
   controller = GetComponent<CharacterController>();
}

/// Update is called once per frame
void Update()
{
    direction.z = forwardSpeed;
    if (controller.isGrounded)
    {
        direction.y = -1;
    }

    
    if(Input.GetKeyDown(KeyCode.UpArrow))
    {
        Jump();
    }else
    {
        direction.y += Gravity * Time.deltaTime;

    }

    //Gather the inputs on which lane we should be

    if(Input.GetKeyDown(KeyCode.RightArrow))
    {
        desiredLane++;
        if(desiredLane==3)
        desiredLane =2;
    }
     if(Input.GetKeyDown(KeyCode.LeftArrow))
    {
        desiredLane--;
        if(desiredLane==-1)
        desiredLane =0;
    }

    //Calculate where we should be in future

    Vector3 targetPosition = transform.position.z * transform.forward + transform.position.y * transform.up;

    if (desiredLane == 0)
    {
        targetPosition += Vector3.left * laneDistance;
    } else if (desiredLane == 2)
    {
        targetPosition += Vector3.right * laneDistance;

    }

    transform.position = Vector3.Lerp(transform.position,targetPosition,80*Time.deltaTime);
}

private void  FixedUpdate() 
{
    controller.Move(direction * Time.fixedDeltaTime);
}

private void Jump()
{
   direction.y = jumpForce;
}

}

#

See the code @keen dew

keen dew
#

Post the !code correctly 👇 and stop pinging me, if anyone can help they'll do so

eternal falconBOT
uncut shard
#

yes

abstract marlin
# faint sluice Does your player have collider?

well i gave him 1 now on the basic settings but then youre spawning on the roof and cant get into the premade pack scene , Y Pos of it is at 0.144 if i change to 0.143 he drops through the ground , everything higher im just spawning on the roof... something wrong with the premade unity pack...

uncut shard
#

@abstract marlin are u talking to me

abstract marlin
faint sluice
abstract marlin
faint sluice
abstract marlin
#

I Also did Read some comments about the pack especially at the testing part of unity learn from that , others had blurry images etc , but no one was just dropping through the scene

#

when i press start i can say byebye to the gamescene from below 😄

faint sluice
abstract marlin
#

the "Controller" is absolutely basic at the opening of the pack , but it doesnt say anywhere that u have to mod it...

faint sluice
#

See the child

abstract marlin
#

oh i didnt looked at the childs , gimme a sec

hot wave
#

for best practice, which part of the fbx should I rotate, the mesh or the name? (like say it is Chair, and underneath it is Chairfbx, which one should i rotate and scale?

abstract marlin
#

the last picture are the missing settings of the player that didnt fit into the first pic anymore

faint sluice
hot wave
faint sluice
# abstract marlin

Ok so your first person controller handles gravity logic for you. And it's "ground" layer is set to "default"

What layer are your floor colliders set at?

faint sluice
abstract marlin
#

you mean this one ?

faint sluice
#

There's no other collider for floor?

abstract marlin
#

carpet itself looks like this , when i select floor i get second picture

#

i dont know where else i should look for it , i mean every tutorial was premade and nothing to twerk , why do i even have to manage this as a beginner just using a tutorial course of unity ?

faint sluice
abstract marlin
#

did this cube , is that what u meant ?

#

gave z a 0.001 and turned off mesh renderer , still falling down

#

ill come back to this tutorial , maybe someday someone updates the download version so it works again , ill just go through an audio video of unity on yt, thanks anyways!
i would have loved to go through that but if its bugged in the 2021 version ill just miss out of the experience 😄

quick kelp
#
   {```
am trying to make a notes inventory but i and into this and kinda have no clue whats wrong
gaunt ice
#
public void Methdo(int a,b)
hot wave
#
    {
        RaycastHit hit;

        if (Physics.Raycast(Camera.main.transform.position,Camera.main.transform.forward, out hit, 2, interactableLayermask))
        {
            Debug.Log(hit.collider.name);
        }
    }```
when i do raycast, it does not detect fbx that have interactable mask, but works with cubes or spheres
#

why does it do that UnityChanThink

#

it works fine with the cubes inside unity, so I tried making my model, but it doesnt seem to log

#

ah, I needed to add a box collider

quick kelp
#

no

lavish gate
#

what type do you want selectedSlot to be?

quick kelp
#

both cause this is the ui slector script

lavish gate
#

public void OnSlotSelected(ItemSlot NoteSlot , ItemSlot selectedSlot) {

#

try this

#

Why do you need it to not be monobehaviour?

static bay
#

What are you trying to do exactly?

lavish gate
#

Lmao i just typed "hmm" and it deleted it

timber tide
#

otherscript script = new()

#

where exactly are you creating this other script otherwise

static bay
#

So you have some instance of "otherscript" elsewhere and you want "classname" to have it too?

#

do you know about constructors?

timber tide
#

c# course time

static bay
#

Then this should be what you want.

timber tide
#

thing with jumping right into unity is that you don't use constructors with monos

static bay
#

Just keep in mind that Monobehaviours CANT have constructors because Unity mumbo jumbo.

#

But for regular classes, all good

timber tide
#

so you miss out on a lot of fundamentals

static bay
#

all good

static bay
#

good times

#

I remember being very scared of arrays with that plugin.

#

Thought they were too complicated.

dusky dirge
#

!code

eternal falconBOT
dusky dirge
#

hey, for some reason when the log is ran, the value of currentGasoline is set to 0, instead of subtracting it by a random value between 15-31. it also isn't updating the text in the component. how can i fix this?

using UnityEngine;
using UnityEngine.UI;

public class GasolineManager : MonoBehaviour
{
    public int startingGasoline = 100;
    private int currentGasoline;
    public UnityEngine.UI.Text gasolineText;

    private void Start()
    {
        LoadGasoline();
        UpdateGasolineUI();
    }

    private void LoadGasoline()
    {
        currentGasoline = startingGasoline;
    }

    private void UpdateGasolineUI()
    {
        gasolineText.text = currentGasoline.ToString();
    }

    public void DecreaseGasoline()
    {
        int decreaseAmount = UnityEngine.Random.Range(15, 31);
        decreaseAmount = Mathf.Min(decreaseAmount, currentGasoline);
        currentGasoline -= decreaseAmount;
        UnityEngine.Debug.Log("Decreased Gasoline. Current Gasoline: " + currentGasoline);
        UpdateGasolineUI();
    }
}
static bay
#
public class ClassName
{
    private Otherscript script;
    
    public ClassName(OtherScript otherScript)
    {
        script = otherScript;
    }

    public void Method()
    {
        //Can now use the variable "script" here without issue.
    }
}
#

When you create an instance of ClassName though, you'll need to "pass in" an OtherScript variable.

#

Is what not everything?

faint sluice
dusky dirge
#

on click

faint sluice
# dusky dirge just once

Do this first

Print initial value before decrement
Then print the value to be decreased right after mathf.min

And then print the remaining value after subtraction is done

dusky dirge
#

good idea

static bay
#

Where are you creating ClassName to begin with? On a Monobehaviour?

polar nova
#

Can someone help me fix this problem? I've been at it for hours and haven't found a solution.

queen adder
polar nova
static bay
#

Actually just for some clarification, when you write out classes, what you're effectively doing is making a "blueprint". If you have a class called Apple and give it a bunch of fields and methods, you're creating a blueprint for an Apple. What you ACTUALLY work with in code are objects, which use these blueprints to define what data they store and what they can do.
So when you do...

new Apple();

You're creating a new INSTANCE of an Apple. Aka an object that has used that Apple blueprint you wrote to define what it can do/store.

queen adder
static bay
polar nova