#💻┃code-beginner

1 messages · Page 276 of 1

flint falcon
#

Start?

wraith valley
#

How?

polar acorn
#

GetComponent is very slow. Do it once and reuse the same renderer

rocky canyon
#

it means not calling GetComponent every single frame.. (which is expensive) u should make a variable and call that getcomponenet in start or awake

polar acorn
# wraith valley How?

Either set the entire position at once, or store it in a variable, modify it, and put it back

rocky canyon
#

then u can use the variable

wraith valley
# polar acorn GetComponent is very slow. Do it _once_ and reuse the same renderer
Unity Learn

Learn about some basic conventions and syntax of writing code - dot operators, semi-colons, indentation and commenting. This tutorial is included in the Beginner Scripting project. Previous: Variables and Functions Next: If Statements

rocky canyon
#

transform.position = new Vector3(transform.position.x, 5f, transform.position.z); this -- how u reckon this would do for ur situation?

flint falcon
#

Awake is where I put them

polar acorn
wraith valley
rocky canyon
rocky canyon
#

to get into good habits

polar acorn
polar acorn
fair steeple
#

Still not printing

polar acorn
fair steeple
#

Nope

#

I have two PlayerInput components now, can that be a problem?

wintry quarry
#

yes

swift crag
#

yup!

wintry quarry
#

that's a problem

swift crag
#

i discovered this during a game jam

wintry quarry
#

one per human being

swift crag
#

it took me way too long to work that out

wintry quarry
#

(or really one per set of input devices)

#

PlayerInput is really designed for local multiplayer

rocky canyon
swift crag
#

the name is quite literal (:

rocky canyon
#

game jams be brutal sometimes

swift crag
#

I use a PlayerInput component so that I can easily access the correct InputUser, but I get all of my input through InputActionReference

fair steeple
#

Still not working 🙃

swift crag
#

I did used to have a big "input manager" that received messages from the PlayerInput component and called other methods

wintry quarry
#

how many PlayerInput components are there

fair steeple
#

Once component

wraith valley
#

How is that? That`s changing y,z

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

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

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E)) GetComponent<Renderer>().material.color = Color.black;
        if (Input.GetKeyDown(KeyCode.Space)) GetComponent<Renderer>().material.color = Color.white;
        if (Input.GetKeyDown(KeyCode.Tab)) GetComponent<Renderer>().material.color = Color.green; Debug.Log(transform.position);

        if (transform.position.y < 5) Debug.Log(transform.position);
       
        if (Input.GetKeyDown(KeyCode.O))
        {

            transform.position = new Vector3(transform.position.x, 5, transform.position.y);
        }
        
        if (Input.GetKeyDown(KeyCode.L))
        {
            transform.position = new Vector3(transform.position.x, 0, transform.position.y);
        }
    }
}
wintry quarry
#

transform.position = new Vector3(transform.position.x, 5, transform.position.y);

wraith valley
#

Thanks

#

My cube teleported to -6.54

rocky canyon
#

is it a child of anything?

wraith valley
#

He was at 0

rocky canyon
#

is the parent at -6?

dreamy urchin
#

guys it is even possible to set animations for a prefab because it doesn't let me do it

wraith valley
#

Just cube

rocky canyon
#

thats a global position.

#

no idea, show ur hierachy of the cube

swift crag
wraith valley
#

Maybe bug

rocky canyon
#

bugs are usually man-made

wraith valley
flint falcon
#

how would I set this up properly if (Input.mousePosition <= transform.position)

wraith valley
#

I don`t know

#

That`s work

rocky canyon
dreamy urchin
#

I tried to add animations to my prefab and said it won't play, why?

swift crag
# fair steeple Just the one

also, is your project actually set to use the new input system? It should have prompted you to switch this when installing the package

flint falcon
rocky canyon
#

ya ofc.. u want to be checking ur mousePosition every frame

swift crag
#

it's "Active Input Handling" in the project's Player settings

fair steeple
#

It was set to both

#

I'm restarting now

#

Let's see

swift crag
#

Both is fine.

rocky canyon
#

Both for the win!

#

imo it should default to both

swift crag
#

The next thing I'd do is to use the Input Debugger window

dreamy urchin
swift crag
#

it's in the Analysis category.

swift crag
#

the Animator component should have a controller assigned to it

fair steeple
#

Alright, I'll see that

swift crag
#

it shouldn't say "None" or "Missing"

rocky canyon
swift crag
rocky canyon
#

seems broken

swift crag
#

When the game is running, the input debugger should be able to show you the currently-enabled action maps and actions

flint falcon
#

@rocky canyon i believe I did it but still have the error CS0019 Operator '<=' cannot be applied to operands of type 'Vector3' and 'Vector3'

rocky canyon
#

ya u cant compare vector3s like that

dreamy urchin
rocky canyon
#

it would be Vector3.x y or z

swift crag
rocky canyon
#

u should be comparing 1 of hte properties of the vector

dreamy urchin
swift crag
#

the animator controller is an asset

#

the Animator is a component that references an Animator Controller

rocky canyon
#

Worker[0] errors ususally go away wiht a restart.. but ive never seen one prefixed to an animator error like that so idk

flint falcon
rocky canyon
#

theres no clips inside that animator

fair steeple
#

Apparently it's working

rocky canyon
# dreamy urchin

open ur animator and drag ur clip into it and set it to be the default clip..

swift crag
#

here, gimme two minutes and i can show you what to look for

fair steeple
swift crag
#

Okay, so that means that those actions are enabled

#

they'd say (Disabled) if they weren't

#

But there should be a list of bindings for each action, like this

dreamy urchin
swift crag
#

(top left corner of the input action asset editor)

swift crag
# fair steeple

The debugger does say that you're using a Keyboard control scheme

#

...but it has no devices!

#

bingo

rocky canyon
#

go to window > Animator and then click ur Attack

swift crag
#

You created a control scheme with no input devices in it.

fair steeple
#

Thanks

swift crag
#

that'll do it (:

dreamy urchin
rocky canyon
#

ahh okay.. then im out of ideas..

fair steeple
#

Thank you for the help

dreamy urchin
rocky canyon
#

maybe ur animation needs a rig set to Humanoid or something

dreamy urchin
flint falcon
#

ok so I have a movement set up with W accelerate and the direction is the mouseposition, but anytime the player gets to the mouse position it shakes back and forth. I am an idiot who cannot come up with a solution

rocky canyon
#

or Default* if its not a humanoid

#

Generic* i mean

#

im just guessing at this point.. maybe you'd have better luck in #🏃┃animation channel

dreamy urchin
#

@rocky canyon it was just a stupid Unity bug, when I try it it actually works, can't stand the amount of bugs it has notlikethis

rocky canyon
#

lol.. glad it was just that..

austere hedge
#

I have a button that I'm trying to change the "Fade Duration" of via script. I figured out how to access the property, but I'm not sure how to set it.

rocky canyon
#

liek i said earlier Worker0 normally means u can ignore it

dreamy urchin
dreamy urchin
swift elbow
rocky canyon
#

ya, its not .colors.fadeDuration

austere hedge
swift elbow
#

.colors and .fadeDuration are completely different lines and vars

rocky canyon
austere hedge
#

Is this right?

rocky canyon
#

neet

rough valley
#

Why are the SerializeField fields not displayed?

rocky canyon
swift elbow
near wadi
#

or forgot to compile

swift elbow
swift elbow
swift crag
#

Yes, but the point is that ColorBlock stores the data that was being asked about

rocky canyon
#

yea but u need to access the ColorBlock to access the fadeDuration

swift crag
#

it stores the fade duration

swift elbow
#

oh mb

rough valley
rocky canyon
polar acorn
swift elbow
summer stump
rocky canyon
#

ur compiler gets stuck @ the error.. and doesn't compile anything more

near wadi
rocky canyon
#

build it out and send them the files

swift elbow
#

itch is free

rocky canyon
#

^ and can use a password

swift crag
#

Itch also lets you send a secret URL to a project

#

I didn't realize that for a while, so I was making it restricted and then putting a password on it

austere hedge
swift crag
#

You must reassign it to the button after modifying it.

rocky canyon
#

like the original example

austere hedge
#

Okay so I think I just need to add

button.colors = cblock;

#

Yep, that's it. Thanks!

flint falcon
#

i give up for the day

dreamy urchin
#

how do I assign a sorting layer to an object?

rocky canyon
#

There's also a Sorting Group Component I think that u can add to ur components.. but thats new to me.

marble cipher
#

I tried to write the code shown in the screenshot, how do I get the parentheses through the void? if so, why is there void movement with me not, can someone explain that (C#)

wintry quarry
swift crag
#
void Movement()
{
  ...
}

This declares a method named Movement. The return type of the method is void, so it does not return anything atlal.

#

I do not know what "get the parentheses" or "why is there void movement with me not" means

dreamy urchin
marble cipher
#

I thought the problem was with the () but through your explanation I understood it now thank you

rocky canyon
#

Movement(); is just how u call the function

#

unity moody today

marble cipher
rocky canyon
#

no worries

ionic zephyr
#

@modest dust using UnityEngine;

[System.Serializable]
public class EffectWrapper
{
public EffectType effectType;
public IEffect effect;

public EffectWrapper(EffectType type, IEffect effect)
{
    this.effectType = type;
    this.effect = effect;
}

} is this correct?

ionic zephyr
tropic marten
#

quick question, what would be the most obvious reason why my gun recoil doesn't work on my player when aiming left and right, but if aiming down at their feet, the recoil pushes the player into the air?

modest dust
eternal needle
modest dust
#

Look at ISerializationCallbackReceiver and the OnBeforeSerialize method

tropic marten
modest dust
#

based on the selected effectType, set the effect accordingly

ionic zephyr
modest dust
#

Lemme check my own EffectWrapper code

ionic zephyr
#

why an scriptable object?

modest dust
#

So that you can drag and drop it

#

If you don't want it then place EffectWrappers directly on the character

ionic zephyr
#

Sorry bro Im really lost with all this

modest dust
#

EffectWrapper is for instantiating a correct class implementing the IEffect interface, based on the enum selected

ionic zephyr
#

but why do I need the enum?

modest dust
#

To know which class to instantiate

#

If you want a projectile ability, you select EffectType.Projectile and it will instantiate ProjectileEffect

#

With any fields you might want to fill in

#

(I think you may need a custom property drawer for that though)

ionic zephyr
#

my god

swift crag
#

i feel like this is going to be way too complicated for a novice to figure out

ionic zephyr
#

yes, I think so as well

#

My mind is exploding right now

#

I am very thankfull anyway

swift crag
#

creating a system that can express a huge variety of abilities through configuration (instead of just writing custom code for each ability) is a difficult task

polar acorn
#

Attempting to solve that problem killed my first Unity project stone dead

#

Just straight up gave up because I couldn't figure it out

swift crag
#

i've also ultra-killed at least one project that way

modest dust
swift crag
#

a real bugbear is when you get to things that aren't just instantaneous effects

#

like playing an animation and then doing something in response to events in the animation

ionic zephyr
#

Its really frustrating because I need this to have progress

swift crag
ionic zephyr
swift crag
#

perhaps we're not on the same page w.r.t. what these abilities will actually do

polar acorn
modest dust
#

A coroutine can be attached if needed / callbacks passed to do things when an animation ends / events trigger

ionic zephyr
#

I can give you a super detailed definition if you want

#

but I think Im going to overload you and you´ve already done a lot for this case

autumn meteor
wintry quarry
autumn meteor
wintry quarry
# autumn meteor

why bare you setting angular velocity and also manually rotating the transform?

stone pilot
frigid sequoia
#

I kinda have a weird question, how does friction work with NavMesh?

stuck palm
#

Why does it work for the up and down but not left and right?

void UpdateMoveInput()
    {
        movementVector = pic.moveVector;
        currentMoveState = movementVector.x switch
        {
            1 => MoveState.Left,
            -1 => MoveState.Right,
            _ => MoveState.None
        };
        currentMoveState = movementVector.y switch
        {
            1 => MoveState.Up,
            -1 => MoveState.Down,
            _ => MoveState.None
        };
    }
autumn meteor
polar acorn
frigid sequoia
wintry quarry
modest dust
# ionic zephyr but I think Im going to overload you and you´ve already done a lot for this case

Anyways, I myself only worked on my own effects system just a few days ago and it was my first time doing anything like this, so it's pretty new to me too. The things I propose might not be enough to handle everything you might want to do - simply because I didn't yet implement it myself so I wouldn't know what would need to be changed or added to support it.. but it's a start, you can expand on what I said or research online / ask others, or simply take a pencil and a piece of paper and plan it out, see what you actually need and how you could implement it

polar acorn
stuck palm
#

how can i avoid that then?

polar acorn
wintry quarry
autumn meteor
polar acorn
autumn meteor
indigo wagon
#

does everything have to inherit from monobehaviour or can it be removed on some codes?

polar acorn
indigo wagon
#

I'm clueless

polar acorn
hushed hinge
#

oh, a part of code add in?

indigo wagon
indigo wagon
#

ok awesome then

#

thank you

swift crag
#

but there is nothing actually touching there

Colliders don't matter, and visuals definitely don't matter

autumn meteor
#

that's exactly where I made a mistake, this is the code for the section that I wrote when I first started studying unity, thanks)

flint falcon
#

@rich adder how do I make it work

frigid sequoia
swift crag
#

how are you pushing the enemies around?

frigid sequoia
#

Should I try with some kind of transform?

swift crag
#

So you've turned off updatePosition on the agent, and you're using a Rigidbody to move the enemy around?

frigid sequoia
#

Like, they don't seem to be interfearing much with each other

swift crag
#

i'm surprised that works at all without some extra legwork

#

I use a CharacterController to move my entities around. I have a NavMeshAgent with updatePosition set to false so that the agent isn't allowed to actually move the entity.

#

I recreated your setup and the object is, indeed, sliding away

frigid sequoia
#

So... you are just using the NavMesh to calculate the path but not moving at all? What do you mean by a CharacterController?

swift crag
#

a literal CharacterController component

#

I ask the agent what its desired velocity is and use that to determine which way to go

swift crag
frigid sequoia
swift crag
#

the behavior with both an agent and a rigidbody is very weird. whilst the agent is moving, it mostly ignores me pushing a cube into it (other than getting moved so that it's not overlapping the cube)

#

but then sometimes it slides

honest vault
swift crag
#

turning on interpolation on the rigidbody makes it stutter constantly

#

presumably since the rigidbody is forcibly setting the position every frame now

wintry quarry
honest vault
wintry quarry
#

Debug.Log in OnDestroy would be a good start

honest vault
wintry quarry
#

Or if you have code that kills the player

#

or destroys it

honest vault
wintry quarry
#

Debug.Log there

honest vault
wintry quarry
wintry quarry
honest vault
#

same thing happened

wintry quarry
#

don't comment it

honest vault
#

ok

wintry quarry
#

I don't know your code at all

#

so it's hard to say where

#

add logs to all the places in your code that destroy anything

honest vault
#

alright lemme see

wintry quarry
#

showing the inspector of your player object would also be a good start

#

maybe it has a particle system or something for example?

tropic marten
#

i can't get my recoil to apply to my player horizontal direction, only in the y direction.
I think i know what line is causing it, but not sure how to correct it?

here's the recoil script:

Vector2 recoilForce = -aimDirection.normalized * recoilStrength;
playerRb.velocity += recoilForce;

and here's the movement script stripped down which i think is blocking it:

void Update()
    {
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
    }
honest vault
wintry quarry
tropic marten
#

do i need Time.Deltatime?

wintry quarry
#

horizontal * speed
This is going to be your horizontal velocity

wintry quarry
tropic marten
#

i was 🙂

wintry quarry
#

Think instead of guessing

#

Look at your code

ivory bobcat
rich adder
flint falcon
#

Lol sorry I must have missed them

#

On mobile have to pull up the code again but basically stopping the ship from jiggling back and forth when it gets to the cursor

ivory bobcat
#

Was he helping you prior?

tropic marten
#

the only was i can see if by doing an if statement bool when recoil is applied

#

but i'm sure thats not the right way about it

wintry quarry
#

before we talk about solutions.

tropic marten
#

yes, the update takes priority

#

meaning its always writing the horizontal

wintry quarry
#

right so you'll need to either do something like use forces to slowly achieve the desired velocity, or disable the normal movement for a time after recoil

#

something along those lines

rich adder
tropic marten
wintry quarry
tropic marten
#

it felt like it stopped allowing the player to control the movement for a splitsecond, especially with a rapid fire weapon

wintry quarry
#

that's what doing that would do, naturally

honest vault
wintry quarry
tropic marten
#

same reason as before i assume?

flint falcon
wintry quarry
rich adder
# flint falcon And I will give that a shot

After you get the distance, if its too close don't let ship go forward etc.
If you want to do it where depends also if mouse behind ship or not, to see if can push forward or back
You can use vector3.dot

flint falcon
minor patio
#

so I have this method that I'm trying to use as a part of a skillset representation in a character creator I'm working on; the trouble is I'm referencing an object ('rep' - the character data) that is currently - you guessed it - null. I know why it's null (I haven't assigned the relevant field yet), but all the tricks I've tried to make it not-null wind up being booby-trapped on me. Kinda just thinking out loud...

stuck palm
#
void UpdateMoveInput()
    {
        movementVector = pic.moveVector;
        if (movementVector == up)
        {
            currentMoveState = MoveState.Up;
        }
        else if (movementVector == down)
        {
            currentMoveState = MoveState.Down;
        }
        else if (movementVector == left)
        {
            currentMoveState = MoveState.Left;
        }
        else if (movementVector == right)
        {
            currentMoveState = MoveState.Right;
        }
        else
        {
            currentMoveState = MoveState.None;
        }
    }

    void UpdateButtonInput()
    {
        if (pic.BPressed)
        {
            currentButtonState = ButtonState.B;
        }
        else if (pic.XPressed)
        {
            currentButtonState = ButtonState.X;
        }
        else if (pic.APressed)
        {
            currentButtonState = ButtonState.A;
        }
        else if (pic.YPressed)
        {
            currentButtonState = ButtonState.Y;
        }
        else
        {
            currentButtonState = ButtonState.None;
        }
    }
```t
#

This works fine enough

#

but if im pressing 2 buttons at the same time, it will just default to none

#

anyone know how i can fix this?

wintry quarry
#

Just write better logic

stuck palm
#

or if im pressing B and X, it will just default to B

wintry quarry
#

You aren't handling diagonals

wintry quarry
#

there's no way to disambiguate with that

ivory bobcat
wintry quarry
#

nah it's an else if

polar acorn
stuck palm
wintry quarry
#

because diagonal is not any of the vectors you're specifically checking for

stuck palm
wintry quarry
#

why are you complicating this so much 🤔

#

why not just directly pass e.g. movementVector to the code that controls the player

#

you're inserting this extra processing layer

ivory bobcat
polar acorn
stuck palm
#

okay i think i know how i want to handle this

#

i want it so its like, if its diagonal, , it only does the last button pressed

meager raptor
#

blue arrow is what's supposed to happen where unit follows marker when spawned, red arrow is what's actually happening

unit spawns outside like it should, but then it just goes towards the building that's supposed to collide, unit is not selectable either because i'll select the building instead if i tried to select unit

does anyone know why this is the case? code is provided here and the spawn marker design

eternal falconBOT
wintry quarry
#

we need more than this

#

no idea what "MoveUnit" does for example

meager raptor
#
public void MoveUnit(Vector3 destination) {
    // Set the destination for the NavMeshAgent to move towards
    if (navAgent == null){
        navAgent = GetComponent<NavMeshAgent>();
        navAgent.SetDestination(destination);
    }
    else {
        navAgent.SetDestination(destination);
    }
}```
wintry quarry
#

I mean it sounds pretty obviouisly like the destination you're setting is wrong

#

so you should log that, and log which object you're using as the destination

#

make sure it matches your expectations

meager raptor
#

okay one sec

#

might've done it wrong, is this what you mean?

#

ill show some more info

wintry quarry
#

and log which object you're using as the destination

#

and then.. you know

#

does this match what you expect?

meager raptor
wintry quarry
#

does this match what you expect?

meager raptor
#

im just grabbing the images

wintry quarry
#

this is looking at a prefab

meager raptor
#

ye it matches

#

yeah

wintry quarry
#

are you sure you're not referencing SpawnMarker from the prefab?

#

You need to reference the one in the scene presumably

meager raptor
#

like this yeah i've assigned it here

wintry quarry
#

you have a lot of prefab overrides here

meager raptor
#

that bad?

wintry quarry
#

It's indicative of disorganization if nothing else

#

so I'm not that confident all your references are pointing the right place

#

anyway... Debug.DrawLine would be helpful for example

#

to establish it's aiming at the right place

meager raptor
#

do i need to do that surely this is simple fix no?

wintry quarry
#

It's probably a simple fix but only once we know what's going on

#

so for now we debug

#

debugging tells us how to fix it

meager raptor
#

problem is the unit isn't following the spawn point when i set it but travels towards the original position when i dont move it, even when i set the pointer at a location it travels to the original position

#

^ just wanted to say that if that gives a better idea

wintry quarry
#

Your code is telling it to do that

#

we just need to figure out why and where

meager raptor
#

will the entire code be useful here

#

here's other one not as long

native seal
#

what is the best way to achieve something like this in rich text through code ?

teal viper
meager raptor
# meager raptor

yeah here @teal viper i spawn multiple units at different points and it prints the same coordinates

native seal
teal viper
meager raptor
teal viper
#

Share the SpawnObject code

wintry quarry
# meager raptor

you still haven't confirmed if those coordinates are what you expect or not

wintry quarry
#

as I said before you're likely referencing the one from the prefab

#

not the one in the scene

rocky canyon
meager raptor
meager raptor
wintry quarry
rocky canyon
#

prefabReference = Instantiate(prefab..
Move(prefabReference);

teal viper
#

*prefabInstance would be a more correct naming.

wintry quarry
#

or spawnedPlayer

#

or whatever it actually is

rocky canyon
#

true true..

#

thingyIWantToBeMovingInsteadOfThePrefab

wicked stratus
#

so I'm working on a save system, and it'd be 1000000% easier, if, when a user makes a new file, there was a way to revert back to the values i set via the edit mode (i.e. say i have a script attatched to an object and the variable floatToChange = 1.0f, but later it's changed and saved as 6.132f and the user wants to make a new save file.) is there a way to do this?

rocky canyon
#

just track ur default values

#

have a Method that resets em

wicked stratus
#

I'm not sure if there's a nice way to do this

rocky canyon
#

its common practice for a settings menu for example

#

i use Scriptable Objects to hold all my data

wicked stratus
#

I have object objects to do this ig

rocky canyon
#

or a class called DefaultValues.. w/ just variables

#

ya, that works just as well

wicked stratus
#

I'm just concerned about writing every variable down manually since there are quite a few entries

rocky canyon
#

whenever i create a new savefile all my data is already there

wicked stratus
#

but i'll do like defaultDict = realDict in start and just copy paste the values in edit mode

#

i have the default for a lot of things- i just have a problem with items that have a ton of entries with unique values

rocky canyon
#

oh yea, ive never done anything that substantial. so i wuldnt know the workflow

#

lol this is as far as ive gotten on the Inventory save system 😢

wicked stratus
#

there are ways i could do it but if theres an easier approach id like to find that before wasting time

rocky canyon
#

i was going to assign an int to each item the player can possess and just read thru them at the beginning of the game and give the player those items..

fair steeple
#

Hey, how do you do OnButtonUp with the new input system? it's surprisingly difficult to find any info on google

rocky canyon
#

the opposite of this..

wintry quarry
rocky canyon
#

the dropdown in Interactions would have a Button up

rocky canyon
#

oh nah it was the 3rd post in that thread.. myAction.cancelled

placid vault
#

Hey yall I need a little helo. I've got a character controller and it works okay but I find that I have to sometimes mash the spacebar button to get my character to move. Anyone know how I might fix this? If it's relevant I'm using 2021.3.15f1, it's an old project of mine but I don't want to bother updating it and risk breaking more stuff lol.

Code: https://pastebin.com/raw/sdTx8CKS

#

!code

eternal falconBOT
wintry quarry
#

input needs to be read in Update

teal viper
placid vault
#

Alright. Let me try to do that. Honestly I haven't touched this project in forever till recently...

wintry quarry
#

you're also mixing up transform.Translate and Rigidbody motion

#

that's a recipe for sadness

placid vault
#

That fixed it. Also not sure what you mean abouting mixing transform.Translate and rb motion. I probably got the original script from someone else on Google ages ago.

stuck palm
#

made a pretty good solution to my controller issue

#

just changed what was handling what and started using the player input actions instead of vectors

wintry quarry
swift crag
#

When you set the position of a transform, you're leaving the physics system in the dark

#

it will just discover that it's in a new position in the next physics update

#

(and if you have Interpolate turned on in the rigidbody's settings, it'll overwrite the position of the transform every frame, so your position gets lost)

swift crag
#

You can set Rigidbody.position to teleport a rigidbody or Rigidbody.MovePosition to immediately move it to a destination

#

(the latter can hit things along the way)

forest depot
#

Hi, I'm trying to make a 2D top down game and when doing collisions, I want to have the player "hug" the walls to give a sort of perspective, but I haven't found a way to get it to work. Right now, he stops far from the top wall, but I want to keep how far he is from the bottom wall. The walls are using a Tilemap Collider 2D and a Composite Collider 2D.

PlayerController Code: https://pastebin.com/h2u13fhg

honest vault
honest vault
toxic flax
#

did you use view.isMine

honest vault
#

Yea

#

its normal when i load in by myself as soon as the other player loads in it switches

toxic flax
#

are these gameobjects already in the scene?

honest vault
#

!vc

eternal falconBOT
#
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

honest vault
#

!cs

eternal falconBOT
teal viper
slim vine
#

!blender

eternal falconBOT
teal viper
timber tide
#

or shaving down the player's collider

#

could do a double player collider such that you've got one near the center of the character, but also one around the character if you're needing the extra detection for attacking, ect

open vine
#

Hey so I recently started learning about PCG and I was able to get a randomly generating map. But can someone point me in the direction of how to do procedural path generation? (I'm trying to create a path along the tiles of the map) Just a process or anything will be helpful thanks!

stuck palm
#

I got basic movement down not linked to physics by making my own psuedo physics calculation and putting it in a seperate class

quartz mural
#

why does this happen when i start the game?

rich adder
#

what is "this" ?

quartz mural
#

the blue screen

#

i think i messed up my camera somehow

#

idk how though

summer stump
#

Show the camera

#

It is likely set to solid color or whatever it is called. Blue is the default for that

#

Also, this is not a code question

charred heart
#

Hi. I'm facing a problem. func() sometimes not even run but returns true.

// call in Update
public void Handle(Func<bool> func)
{
    bool done = func();
}
wintry quarry
#

Well you're storing it in a local variable that you don't do anything with

#

What makes you think it isn't running though?

quartz mural
charred heart
wintry quarry
summer stump
charred heart
#

it did run, i did put debug.log in handle too

wintry quarry
quartz mural
wintry quarry
#

Trust me it can't return anything if it's not running

summer stump
quartz mural
#

mb

#

oh i see now

#

before it was the map

#

and ive connected it to player

#

all of a sudden its going to its default color?

charred heart
# wintry quarry Trust me it can't return anything if it's not running
public void Handle(Func<bool> func)
{
    if (_doneFlag) return;
    _timer += Time.deltaTime;
    bool done = func();
    Debug.Log(done.ToString() + (transform.position - _destination).magnitude.ToString() + ((transform.position - _destination).magnitude < _stopDistance));
    if (done && (_behaviorPath.GetCurrentAction().ActionDuration() < _timer))
    {
        _doneFlag = true;
        _doneAction = true;
        _timer = 0f;
    }
}

public bool Move()
{
    if ((transform.position - _destination).magnitude < _stopDistance)
    {
        if(!_navMeshAgent.hasPath && _navMeshAgent.velocity.sqrMagnitude == 0f)
        {
            Debug.Log("Move true " + (transform.position - _destination).magnitude);
            return true;
        }
    }
    Debug.Log("Move false");
    return false;
} 

public override void FixedUpdateState()
{
    base.FixedUpdateState();
    _npcController.Handle(_npcController.Move);
    
}
wintry quarry
#

Is it the one right above?

#

What is the type of this script? What's the type of that NPC variable?

#

Not clear

quartz mural
#

@summer stump bro?

charred heart
wintry quarry
#

It might not be

#

This isn't enough code to be sure

rich adder
charred heart
# wintry quarry This isn't enough code to be sure

Move() and Handle() method are implement at NPCController class

public class NPCMoveState : NPCMovementBaseState
{
    public NPCMoveState(MonoBehaviour entityController, Animator animator) : base(entityController, animator){}
    public override string StateName => "Move";

    public override void EnterState()
    {
        base.EnterState();
        _animator.CrossFade(LocomotionHash, 0.1f);
        _npcController.OnMove();
    }

    public override void FixedUpdateState()
    {
        base.FixedUpdateState();
        _npcController.Handle(_npcController.Move);
        
    }
} 
wintry quarry
#

This still doesn't tell us what _npcController is

quartz mural
charred heart
# wintry quarry This still doesn't tell us what _npcController is

It's a class inherits from monobehavior, i create it for NPC control

public class NPCController : MonoBehaviour
{
    [SerializeField] private BehaviorPathTransition _behaviorPath;

    [SerializeField] private bool _doneAction = true;
    private BaseStateMachine _movementStateMachine;
    private BaseStateMachine _actionStateMachine;
    private Animator _animator;
    ...
}
wintry quarry
#

If it enters the first if statement but not the inner one

#

It is still running though

charred heart
wintry quarry
#

Can you show your console window

#

To prove it "is not running"?

quartz mural
#

@rich adder sorry bro im not understanding it was fine before idk what i did

#

i mightve miss clicked smt a while ago

#

and idk what it is

#

can you just explain to me what to d

#

u sed smt abt skybox?

rich adder
#

no way of us knowing what its supposed to look like
also not really a code question.

quartz mural
#

cmon man plz

#

no one on other ones answer

#

until the next day

#

shall i just delete and get it tagin

#

nvm that didnt go well

rich adder
#

you haven't really explained whats wont with the blue

quartz mural
#

ok

#

so noramlly

#

the camera will show whats on the scene

rich adder
#

all i see is that camera has SKybox set but its blue, meaning Lighting tab has no skybox material assigne

summer stump
quartz mural
summer stump
#

Too close to the map probably

rich adder
summer stump
#

Check z levels

quartz mural
#

i mightve miss clicked smt earliernot sure wat it is

#

z levels?

rich adder
#

the camera should prob be -10

#

right now is at 0 , thats prob wrong

summer stump
quartz mural
#

YEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEES

#

THANKS MY BRO

summer stump
#

Cameras won't render things they are too close to

quartz mural
#

APPRECIATE U GUYS

summer stump
quartz mural
#

yes

#

thank sbro

#

appreciate u

charred heart
wintry quarry
#

Nor any of the log from the Handle function

#

None of this code is running at all

quartz mural
#

@summer stump one last thing

#

the size of my camera got messed up

#

z is -10

#

wats x and y

#

default

hushed hinge
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ButtonDoor : MonoBehaviour
{
    public int buttonNumber; // The button number assigned in the inspector
    public AudioClip buttonPressSound;
    public Sprite pressedButtonImage;
    public Sprite normalButtonImage;

    private List<int> correctOrder = new List<int> { 1, 2, 3, 4 };
    private List<int> pressedButtons = new List<int>();

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            // Play sound and change image to pressed state
            AudioSource.PlayClipAtPoint(buttonPressSound, transform.position);
            GetComponent<SpriteRenderer>().sprite = pressedButtonImage;

            // Add the button number to the pressedButtons list
            pressedButtons.Add(buttonNumber);

            // Check if the pressed buttons match the correct order
            if (pressedButtons.SequenceEqual(correctOrder))
            {
                // Trigger fade animation on the Lock object
                GameObject lockObject = GameObject.Find("Lock");
                Animator lockAnimator = lockObject.GetComponent<Animator>();
                lockAnimator.SetTrigger("FadeOut");
            }
            else if (pressedButtons.Count == correctOrder.Count)
            {
                // Reset button states if incorrect order
                ResetButtonStates();
            }
        }
    }

    private void ResetButtonStates()
    {
        // Reset pressed buttons and change image back to normal state
        pressedButtons.Clear();
        GetComponent<SpriteRenderer>().sprite = normalButtonImage;
    }
}

I got this error which I don't get

charred heart
#

I don't see any Move False or Move True

queen adder
#

gpt forgetting usings UnityChanOops

hushed hinge
rich adder
hushed hinge
#

oh

rich adder
#

the function you copied and pasted is missing the namespace to help "find" it

north kiln
# hushed hinge mising LINQ?

Your IDE should be able to add the missing namespace. If it's not underlining errors in red you need to configure it. !ide

eternal falconBOT
rich adder
#

ctrl + . on the red underline if you have it, it should suggest it

rich adder
summer stump
rich adder
#

if i recall correctly yours is Visual Studio and is configured

summer stump
rich adder
hushed hinge
summer stump
#

They have definitely heard of it before

rich adder
#

yeah they do that lol "you need this to be a variable"
"A variable? ?"

rich adder
hushed hinge
#

I pressed ctrl + . but nothing is happening

rich adder
sharp ferry
#

Need some help here what do you guys think is the best way for camera following I've heard a few options

  1. Cinamachine
  2. Lookat
rich adder
#

Cinemachine

sharp ferry
#

Its that good?

rich adder
#

anything camera, always cinemachine

#

ya Unity wouldn't have bought it otherwise lol

sharp ferry
#

Gotchu gonna take a look

rich adder
#

you can also use the 💡

hushed hinge
#

oh, but there were no underline for me

#

ok, i got it

polar acorn
eternal falconBOT
long steppe
#

hey i know this is a super beginner question but i'm trying my hand at a recreation of pong, how do i stop the paddle from continuing to float upwards after i've stopped pressing w? i have a screenshot of my code but i don't really know how to show you what the paddle is doing lol

rich adder
#

Could also just use GetAxis for Vertical and it gives you W/S or UpArrow/DownArrow with float value

long steppe
#

sweet thank you i'm still learning what functions and methods i have available to me lol

summer stump
vale karma
#

what would I put in place of the Debug.Log("Success!"); in order to make the object transform its position to the object that the raycast hit?

cosmic dagger
vale karma
#

okay, i didnt think it was so difficult, fsr im getting tutorial hell syndrome from this lil road block

cosmic dagger
#

this task is not difficult. it's very simple and only one line of code . . .

#

you have to look at the information provided to you . . .

vale karma
#

yeeyee

cosmic dagger
#

if you have the object the raycast hit, then you have access to its position, therefore, you can assign the original object's position to that position . . .. . .

vale karma
#

bro this has colliderinstanceID? so many things i could do with this, macadamia nuts, almonds, walnuts, acorns

rich adder
#

why would you need colliderinstanceID?

vale karma
#

i dont, just got distracted

#

wahts an articulation?

rich adder
#

something to do with joints

fluid crane
#

Hey guys, im helping a friend to start coding in C# Unity.
but his editor seems strange, the Debug.Log does not got autocompleted neither have color

#

Anyone knows what's missing?

#

He is using VIsual Studio 2022

rich adder
#

assuming the Unity Workload is already installed..

fluid crane
rich adder
#

yesterday is not today lol

fluid crane
#

it worked doing Solve Errors

#

xD

#

omg 4 am looking for weird bugs eheh

eternal falconBOT
vale karma
#

!code

eternal falconBOT
vale karma
#

whats that other one? it allows multiple pages of code?

limpid wren
#

Not entirely sure I understand how the CollisionMatrix affects the calling of OnTriggerEnter2D. Does it only work on OnCollisionEnter?

vale karma
#

im not using any colliders with ontrigger, just using it as a visual

limpid wren
#

Sorry, it wasn't related to your question

hot harbor
#

Is it impossible to subscribe to scriptableObject functions? I've been getting reference is not an instance of an object errors when I try to do this. I'm trying to hook up InputActions with one of my scriptableObject function that handles shooting

vale karma
#

im thinking my update function is still saying that grabpoint isnt null, so it moves it to the presumed grapoint location, and oo my bad 😮

limpid wren
#

I've set up my CollisionMatrix to have "pickups" affect only "pickupZones" and yet OnTriggerEnter2D gets called when anything touches it

cosmic dagger
limpid wren
#

That... does not make a lot of sense for me

polar acorn
rocky canyon
#

nvm im wrong

#

it does ignore

#

i put the wrong layer on it

limpid wren
#

I exclusively have one object with PickUp and one object with PlayerPickupZone

rocky canyon
#

ya, only colliders w/ pickup should interact with playerpickupzone

polar acorn
limpid wren
rocky canyon
#

something more is going on.. do you have the layers set up correctly on each object?

wintry quarry
limpid wren
wintry quarry
#

there is indeed

cosmic dagger
#

indeed there is . . .

rocky canyon
#

praet with teh clutch

summer stump
#

is indeed there

limpid wren
#

You are indeed correct

#

I had not set up the correct collision matrix, thanks!

solid bough
#

i have two scenes
my character has dontdestroyonload
but when he goes to the other scene, all the other objects in there (enemy, camera) and their scripts don't have the player set as their reference
how do i go about making it work?

wintry quarry
#

If there's only one player you can go with the singleton pattern - using a static reference field.

#

Another option of course is FindWithTag

solid bough
wintry quarry
#

Yes of course you could do that

#

there are many ways to solve the problem

solid bough
#

and which way is the cleanest/most optimal one? how do they do it in Hades where you move through rooms and your character stays the same across

wintry quarry
#

Doing that copying of stats will require similar referencing tricks though - you'd need something to track the stats across scenes

wintry quarry
#

every game is different

solid bough
#

well, if i were you and i were to do a very simple two rooms game with coins you gather through the rooms and want to keep the coin counter and some other arbitrary stats
which way would you personally do? 🥹

thin hollow
#

I have a line of coded i dont understand

int damageToTake = ignoreDefence ? damage : CalculateDamage(damage);

im not familiar with the colon and the questionmark

cosmic dagger
thin hollow
#

it was someones code i was looking at

nimble apex
thin hollow
#

ok so is that basically what its saying

nimble apex
#

<condition> ? if : else

summer stump
cosmic dagger
nimble apex
#

i dont wish to see my projects or my teams project got infested by ternaries if tho lmao

#

its hard to figure them out if the ternaries got too long

cosmic dagger
#

there is no reason to nest ternaries. that would definitely be hard to read . . .

nimble apex
#
if(A == B) {
    doA();
}else{
    doB();
}```
im okay with this 
```cs
(A == B) ? doA(); : doB();```
cosmic dagger
timber tide
#

ternary stuff is ugly

nimble apex
#

sad

cosmic dagger
#

you can create an extension method to fix that . . .

wintry quarry
#

I was kinda curious - and this is the least ugly I could get "ternary with void methods"

void A() {}
void B() {}

void C() {
    Action x;
    (x = (true ? A : B))();
}```
cosmic dagger
#

now i use a boolean extension so it doesn't look too bad . . .

void A() { }
void B() { }

true.Ternary(A, B)();

public static Action Ternary(this bool b, Action @true, Action @false) => b ? @true : @false;
wintry quarry
#

why not just invoke them inside

#

then you don't need the extra ()

#

but yeah that's cute. I was just thinking a static non-extension too.

cosmic dagger
wintry quarry
#
public static void Ternary(this bool b, Action @true, Action @false) {
  if (b) @true();
  else @false();
}```
#

then it's just cs true.Ternary(A, B);

cosmic dagger
#

oh, i see, by removing the ternary and changing the return type to void . . .

wintry quarry
#

Oops I accidentally the void 😆

cosmic dagger
#

yeah, i returned an Action in case of assignment . . .

#

i guess it's not really needed . . .

static bay
ivory bobcat
#

It would be relative to aesthetics.

swift sedge
hoary ice
#

how do you do something like this? a list (elements) within a list (plain font, outline font, outline shadows font, shadows font)?

languid spire
hoary ice
#

i dont understand sir, can you give me an example?

languid spire
#
class A {
public Font aFont;
}

class B : MonoBehaviour {
public List<A> aFontList;
}
eternal needle
#

along with putting [Serializable] above class A

long steppe
#

not entirely sure where i'm supposed to post this, but every time i press play in the editor and press a button to move, the entire unity editor freezes and becomes unresponsive and i'm forced to close it in the task manager, are there any common reasons this happens?

languid spire
long steppe
exotic hazel
#

Hey guys.This code spawns 10 rocks on random coordinates in my terrain.I used sample terrain to get the y coordinate but the Y coordinate isnt coming correct.The first rock always spawn on y lvl 0 and then rest on random coordinates. could someone help me

#

i have this error since yesterday but couldnt get any reason

languid spire
#

Dont you think it might be a good idea to only use Ycoords AFTER you have calculated it?

exotic hazel
#

wdym

languid spire
#

read your code from top to bottom

exotic hazel
#

ok

#

oh

#

This is the same

#

without loop and it works

astral falcon
#

I bet your first ycoordinate is always 1?

languid spire
#

No it doesn't

#

code is executed from top to bottom, you cannot read a value before you have written it

exotic hazel
#

it works ive already tested it

#

lemme try it tho maybe i missed something there

languid spire
#

then your testing is faulty, that code as written does not work

astral falcon
ruby python
#

!code

eternal falconBOT
ruby python
#

Mornin' all. I think I'm having a bit of a spanner moment.

Really simple onTriggerEnter.

Script lives on an object that hits the 'SectionRemover' object and should get destroyed (yes, this will be pooled once it's working).

Weird thing is, the debug is being fired, but the object isn't getting destroyed.

Am I being an idiot? lol.

private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("SectionRemover"))
    {
        Debug.Log("Collision");
        Destroy(gameObject);
    }
}
timber tide
#

It will be destroyed at the end of the next fixed update

ruby python
#

The object(s) never get destroyed though. 😕

timber tide
#

You sure you're not expecting the other.gameObject to be destroyed?

ruby python
#

In the video, this script lives on the 'ground rocks' so when they hit the two objects that form the V Shape they need to be destroyed. As you can see, the debug gets triggered, but the objects remain. It's very odd.

timber tide
#

For the heck of it, try just disabling the gameobject

ruby python
#

Okeydoke. uno momento 🙂

timber tide
#

or print out the object being destroyed

keen dew
#

There's hundreds of those log messages. How do you know the logs for those rocks specifically are being printed?

ruby python
#

Aaah, I see what's going on. It's the LOD's, I have two of the objects that don't have LOD's set up yet, and they disable fine, it's the LOD'd one that aren't. Sokay I know how to fix that.

#

So yeah, was being an idiot. lol.

ebon robin
#

how to stop these clones from floodign the scene

languid spire
ebon robin
#

But Im Object Pooling

#

destroy takes a lot of resources

languid spire
#

in that case parent them to an empty game object

ebon robin
#

good idea

#

thanks ill try that

smoky mauve
#

why isn't my variable showing on the inspector?

undone rampart
#

the workarround is to create a serializable struct containg your other array and make a list of that struct

smoky mauve
#

oh, ok ty

amber spruce
#

how do i check a list or array to see which item has the correct value for example lets say i have a list of boxes with a number variable attached i want to find the one that number variable is 5 how would i do that

ornate lynx
#

hello, i've encountered a problem in visual studio, the code works, but Monobehavior and Rigidbody2D aren't being highlighted. i've followed the fix that've been refered to by a lot of websites, but that doesn't seem to fix the problem. how can i fix this? https://forum.unity.com/threads/intellisense-not-working-with-visual-studio-fix.836599/

burnt vapor
eternal falconBOT
ornate lynx
rare basin
#

how is that related

#

to have configured IDE

ornate lynx
#

idk i'm just saying

#

doesn't that mean the ide is interacting with unity :/ ?

burnt vapor
#

Your ide does not interact with Unity, it just supports you with the code you write

#

Currently it does not support you with Unity related code

#

Once configured it will work

ornate lynx
#

i'll try to

shrewd ruin
#

How do you guys feel about || Russia || ?

silk night
shrewd ruin
#

Yes, I understand... By the way. Could you tell me what are the main differences between version 2023.2.15 and Unity 2022.3.22f1?

languid spire
shrewd ruin
languid spire
#

do not use a non LTS version unless you really know what you are doing

shrewd ruin
#

Guys, maybe someone has a good template for a Shooter ||unitypackage|| ?

thorn holly
silk night
swift crag
#

List<T> already has a FindIndex method.

shrewd ruin
#

Does anyone understand Photon?

swift crag
#

It takes a System.Predicate<T>, which is a function that takes a T and returns a bool

#
List<int> nums = new() { 1, 5, 3, 5, 7, 8, 0 };
int index = nums.FindIndex(x => x == 5);
#

another example

silk night
#

oh yeah i forgot first outputs the value, not the index 😄

swift crag
#
List<MyClass> things = new();
int winner = things.FindIndex(thing => thing.IsCorrect());
#

if you've never seen the => syntax used like this before, this is creating an anonymous function

#

it's a function with no name

#

you're probably used to seeing things like this

#
void Update() {
  // do stuff here
}
#

this is a method: a function with a name that's part of a class

#

Anonymous functions are useful for writing logic that you only use in one place

#

So both of these would work equally well

#
private bool Decider(int input) {
  return input == 5;
}

public int FindIndex() {
  return myList.FindIndex(Decider);
}

public int FindIndex2() {
  return myList.FindIndex(num => num == 5);
}
#

assuming that myList is a List<int>

#

anonymous functions can capture variables, too, which is useful

#
public int FindIndex3(int desired) {
  return myList.FindIndex(num => num == desired);
}
thorn holly
#

So would it look like? ```cs
private bool Decider(MyClassName input) {
return input.variable == 5;
}

swift crag
#

Right.

thorn holly
#

This is new to me too so I’m curious

swift crag
#

the parameter should match the type the list contains

#

and then it should do some work and return a bool

thorn holly
#

Out of curiosity, how do you make a method that passes a function as an argument?

#

Like what’s the syntax for it?

vapid tendon
#

Suppose I have a button on the canvas, and some objects in the scene that respond to clicks.
How do I make it so that, even if a canvas button overlaps with some other object in the scene, when I click the canvas button, don't make the other object respond?

things I know and have tried:
I know how to use OnMouseDown etc to detect a click on a collider, I recently found out about OnPointerClick etc to detect a click on a UI element on the canvas, and when searching I sometimes see Input.GetMouseButtonDown(0) for generic click detection.
I tried to overlap a canvas element and a scene element, and when I clicked, both object's click events triggered. I don't know the order of operations here so I don't think I can set a flag in the canvas element that makes the scene element do nothing on click.

timber tide
#

there's usually a bool on most UI components that say like Raycast target, or Blocks Raycast (meaning it takes in raycasts hits)

#

oh but you're saying both are activating

#

I'd stick to a single method, preferably OnPointerClick interfaces and friends.

vapid tendon
#

Turning off "raycast target" makes the canvas object's click event go away, but still triggers the scene object's click event.

amber spruce
#

also im trying to make a list / array containing all gameobjects that have the playerstats script on them im not exactly sure if im doing it right here is what im trying

PlayerStats[] playerstats = PlayerStats.FindObjectsByType(PlayerStats, true, false);

is that a bad way to do it (i also know that has a error im looking at the documentation right now to fix that)

timber tide
burnt vapor
#

I guess in this case you want to collect the components for stats so I guess it makes sense to do this here

swift crag
#

System.Func<int, bool> takes an int and returns a bool

#

They're called delegate types.

thorn holly
#

Hmm, interesting

thorn holly
#

So his would be System.Func<MyClass, bool>

swift crag
#

You can declare your own delegate types to get something with a name and with named parameters

#
public delegate bool MyPredicate(int input);
timber tide
#

Oh, IPointer does also use a physics query, but also the graphics raycast?

#

I never thought about tossing that on 3D objects

stone pilot
#

is there a way to adjust pixel perfect camera size without ruining the resolution ?

vapid tendon
#

For your information:

  • My canvas object has an Image and a SimpleClickLogger (script).
  • My scene object has a Sprite renderer, a Box collider 2D, and the same SimpleClickLogger script.
  • The script contains both OnMouseDown and OnPointerClick.
    • The canvas object only fires the OnPointerClick, the scene object only fires the OnMouseDown.
swift crag
#

but the camera is only going to be able to snap to certain zoom levels

potent echo
#

Hello. I'm trying to make an enemy that moves along the exact route that the player took. Any ideas on how I could go about this?

timber tide
stone pilot
timber tide
#

or vice versa

vapid tendon
#

Is that documentation available for Unity 2022? (Sometimes I google some docs, it gives me 2018 or 19, and when I switch to 2022, I can't find the relevant doc)

timber tide
#

I did try finding the most recent docs of it, but it's giving me a hard time.

swift crag
timber tide
#

It's not deprecated though

vapid tendon
#

2022 doesn't have a page for UnityEngine.EventSystems on the side bar ... somehow

thorn holly
burnt vapor
#

More efficient would be saving vector2 points, only if the direction changes substantially

swift crag
#

This is a common annoyance. I'll get old documentation from when it used to be part of the "core" libraries

#

(I also prefer the old documentation's look to that of the package docs, tbh...)

vapid tendon
#

Thanks, I guess. Package docs are ... more annoying in my experience too (had more trouble finding how to change text in a TextMeshPro text component, had to resort to google and chatGPT)

swift crag
#

the TMPro documentation is..not great

timber tide
#

enjoy reading through the 300 methods without any comments

burnt vapor
#

The ultimate "Try It and See" experience

swift crag
#

i'm trying to learn to do more complex TextMeshPro stuff without just copying code from examples and modifying it

#

but...yeah

sullen grove
#

Any good character controller script that Does not slide around on the floor

swift crag
#

a character controller does not "slide around" unless you tell it to

#

so, most scripts that use a CharacterController will already do this

hidden sleet
#

Currently trying to do an enemy LOS detection system, but I don't think I'm doing the raycast right since it can see right through the obstacles. ```cs
void Update()
{
Debug.DrawLine(transform.position, targetLocation.position);
detectionAngleRadians = detectionAngle * Mathf.Deg2Rad;
detectionAngleFloat = MathF.Cos(detectionAngleRadians);
targetVector = targetLocation.position - transform.position;
distanceToTarget = Vector3.Magnitude(targetVector);

        if ((Vector3.Dot(transform.forward, targetVector) > detectionAngleFloat && distanceToTarget < detectionRange) && entitySpotted == false)
        {
            Ray ray = new Ray(transform.position, targetLocation.position);
            
            if (Physics.Raycast(ray,out RaycastHit hit, distanceToTarget + 1F, obstructionMask))
            {            
                OnPlayerSpotted.Invoke();
                entitySpotted = true;
            }
            else
            {                    
             
            }
        }
        else if ((Vector3.Dot(transform.forward, targetVector) < detectionAngleFloat || distanceToTarget > detectionRange) && entitySpotted == true)
        {

            Ray ray = new Ray(transform.position, targetLocation.position);
            if (Physics.Raycast(ray, out RaycastHit hit, distanceToTarget + 1F, obstructionMask))
            {                    
                
            }
            else
            {                    
                Debug.Log("Player has vanished");
                OnPlayerVanished.Invoke();
                entitySpotted = false;
            }
        }
    }
#

swapping them over yields the same result. And I've definitely got the layermask set up in the inspector and on the walls

wintry quarry
#

A ray takes a position and a direction

#

you've given it two positions

hidden sleet
#

ah, I thought it was a start position and end position

#

gotcha

wintry quarry
#

If you want to cast between two points you can use Physics.Linecast
Linecast takes start and end positions

queen adder
#

why does my mouse shows error

wintry quarry
#

The error message will tell you what the problem is.

queen adder
#

unless that's the font there's a space between the Debug and log function

wintry quarry
#

there is a space there but it doesn't matter and isn't related to the error.

queen adder
#

then?

wintry quarry
#

share it with us if you don't understand it

queen adder
wintry quarry
#

but clearly you're missing using UnityEngine.InputSystem;

#

your IDE should suggest this for you automatically

hidden sleet
stuck palm
#

is there a way t o not use new Vector2's every time? this is normally called each frame, so idk if its very efficient.

public static Vector2 MoveX(Vector2 velocity, float inputDirection, float speed)
    {
        Vector2 moveDirection = new Vector2(inputDirection * speed, velocity.y);
        return moveDirection;
    }
wintry quarry
queen adder
#

Hey, so I'm trying to trigger a scene switch inside my game that would bring up an options scene and inside that scene use an attached script to resume the game, but I'm getting a runtime error where none of my inputs are reading in despite both scripts being properly attached. Do I need to instantiate a Scene object and check for its .BuildIndex inside Update() instead?

      //GameController.cs
        void Update() {
        if (Input.GetKeyDown("p"))
        {
            SceneManager.LoadScene(2); // Brings up option scene
        }
        }
     
        //OptionsBehavior.cs
        void Update() {
        if (Input.GetKeyDown("p"))
        {
            SceneManager.LoadScene(2); //Returns to game scene 
        }
        }
      
sullen grove
#

Dose anyone know why my Character controller script slides around

wintry quarry
sullen grove
queen adder
wintry quarry
#

Add Debug.Log to make sure your code is running when you expect it to run.

queen adder
#

yep did that to test and no output

wintry quarry
#

then your code isn't running at all

queen adder
ivory bobcat
eternal falconBOT
wintry quarry
#

Also both of your scripts seem to load the same scene (scene 2)

stuck palm
wintry quarry
#

unless they are marked with ref out or in

stuck palm
#

I've learnt something new today 😊

wintry quarry
#

then there are special rules.

stuck palm
#

I've seen ref before,what does it do?

#

Like with overlap nonalloc or something

wintry quarry
#

ref passes a variable in by reference

#

instead of by value

queen adder
#

I can share the whole script if that would help

wintry quarry
#

yes the whole script would help.

hidden sleet
#

Now i'm noticing that it ends up drawing a line from the centre of the world to the enemy instead of the enemy to the player, which is odd. it's drawing a line from the enemy to the hit point, so shouldn't that just point to the player? Don't know if i've just gone barmy and forgotten something. ```cs
void Update()
{
detectionAngleRadians = detectionAngle * Mathf.Deg2Rad;
detectionAngleFloat = MathF.Cos(detectionAngleRadians);
targetVector = targetLocation.position - transform.position;
distanceToTarget = Vector3.Magnitude(targetVector);

        if (distanceToTarget < detectionRange) //Target is within range
        {
            if (Vector3.Dot(transform.forward, targetVector) > detectionAngleFloat) //Target is within FOV
            {
                Ray ray = new Ray(transform.position, (targetLocation.position - transform.position).normalized);

                if (Physics.Raycast(ray, out RaycastHit hit, distanceToTarget + 1F, obstructionMask))
                {
                    //Hit object
                    Debug.DrawLine(transform.position, hit.point);
                    OnPlayerVanished.Invoke();
                    entitySpotted = false;
                }
                else
                {
                    //Hit target
                    Debug.DrawLine(transform.position, hit.point);
                    OnPlayerSpotted.Invoke();
                    entitySpotted = true;
                }
            }
            else //Target is outside of FOV
            {
                OnPlayerVanished.Invoke();
                entitySpotted = false;
            }
        }
        else //Target outside of range
        {
            OnPlayerVanished.Invoke();
            entitySpotted = false;
        }
    }
#

Ah, just noticed those errors

#

not sure why it's saying there's a null reference when each state appears to be using the detection system fine

ivory bobcat
#

You've got it collapsed so order isn't known

queen adder
wintry quarry
#

that would be Menu.cs and PlayerMovement.cs

queen adder
#

sorry, PlayerMovement.cs = GameController, I just gave it a different name 😅

#

I never shared something called Menu.cs though

wintry quarry
#

which is still not related to the searches

queen adder
#

💀 my bad

#

renamed

wintry quarry
#

the filename needs to match the class name

queen adder
#

yep I changed the class name

wintry quarry
#

when are you doing all this

wintry quarry
#

So if you just did it now go re-check that the scripts are attached properly and try again

queen adder
#

just did 👍

#

apologies for the confusion

#

you reckon the above component might be interfering with it @wintry quarry? there aren't any overlapping keybinds methinks

#

I'll disable and try

wintry quarry
#

unless you have active input handling set to Both in project settings

#

have you shown your console window yet?

queen adder
#

could always be a VS quirk, but I noticed that the highlighting for the function in the file where it's not working isn't on

#

oh. my. god.

queen adder
#

and now it works

#

ty for the help

ornate lynx
whole idol
#
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using UnityEngine;

public class GameInput : MonoBehaviour
{

        private PlayerInputActions playerInputActions;
        private void Awake()
        {
            playerInputActions = new PlayerInputActions();
            playerInputActions.Player.Enable();

            playerInputActions.Player.Interact.performed += Interact_performed;
        }
        private void Interact_performed(UnityEngine.InputSystem.InputAction.CallbackContext obj)
        {
            OnInteactAction? Invoke(This, EventArgs.Empty);
        }
        public Vector2 GetMovementNormalized()
        {
            Vector2 inputVector = playerInputActions.Player.Move.ReadValue<Vector2>(); ;

            inputVector = inputVector.normalized;

            return inputVector;

        }


}

wtf is my error here?

timber tide
#

your error is not posting the error

summer stump
wintry quarry
#

but yeah show error