#šŸ’»ā”ƒcode-beginner

1 messages Ā· Page 91 of 1

queen adder
#

Okay then just make it not a local like

float timer = 0;
private void Update() {
  timer += Time.deltatime;
  // the rest
}
acoustic arch
#

how do i make it so that when i rotate the player it's always facing forward on the x-axis

#

i have to make it a child object of something right?

queen adder
#

Depends on how you rotate it

#

Mouse movement i guess?

#

Or key presses

acoustic arch
queen adder
#

oh and also

#

3d?

rare basin
#

so how do you want to rotate him and keep him facing fowrad on the x axis on the same time šŸ¤”

#

do you have head as a separate object?

acoustic arch
#

just so that i move forward in the direction their looking

rare basin
#

you just said you want to rotate

acoustic arch
queen adder
#

This is what I do usually

public class Player : Monobehaviour {
  private InputManager _inputs = InputManager.Instance;

  [Header("Rotation Values")]
  [SerializeField] private float sensX = 20f;
  private Vector2 rotation = Vector2.zero;

  private void Awake() {
    if (_inputs == null) _inputs = InputManager.Instance;
  }

  private void Update() {
    // Basically just get the rotation.x value from your horizontal mouse movement,
    // Idk what way you do it yourself, but it should be pretty easy.
    rotation.x += _inputs.GetLookInput().x * Time.deltaTime * sensX;

    Quaternion yaw = Quaternion.AngleAxis(rotation.x, Vector3.up);
    transform.localRotation = yaw;
  }
}
#

Not 100% sure its gonna work the way you want it to work, idk how your project and other code is set up

#

but it'll rotate the player character left or right

acoustic arch
#

i think my code and everything is all good i just need to make it rotate locally

queen adder
#

fps controller?

acoustic arch
#

yeah

queen adder
#

oh

acoustic arch
#

i'm using RigidBody

#

not character controller

shell herald
#

how do i check if i get inputs from a controller or from keyboard&mouse

queen adder
rare basin
#

on new input system

#
            InputDevice inputDevice = InputSystem.devices[0];

            if (inputDevice is Keyboard || inputDevice is Mouse)
            {
                Debug.Log("keyboard/mouse");
            }
            else if (inputDevice is Gamepad)
            {
                Debug.Log("controller");
            }    
shell herald
#

thx

#

and why doesnt this work?

languid spire
shell herald
#

how would i do it correctly?

languid spire
#

what are you trying to say with that line?

shell herald
#

if i get an input corresponding to Fire2, it should fo these lines

languid spire
#

so why (0) ?

shell herald
#

oop, i originally had it at "Input.GetMouseButtonDown(0) and simply forgot

teal viper
#

You even underlined the line! How did it not ring any bells??šŸ˜…

shell herald
#

but even without the 0 it doesnt work

languid spire
#

true because GetAxisRaw does not return a bool

teal viper
#

Does it throw an error? Read it.

shell herald
#

the error is "method name expected

languid spire
#

what? show code

shell herald
languid spire
#

so? if GetAxisRaw is what?

shell herald
#

what does getaxis raw actually give me? is it a range from 0 to 1?

languid spire
#

read the docs

teal viper
# shell herald

The compiler is confused. It doesn't understand what you are trying to do.

languid spire
#

neither does the programmer apparently

shell herald
#

thats why im in the beginner channel. i dont even understand how to read the unity scripting docs because the entire page is built like a hierachy

honest idol
#

can someone help me I keep getting this error when ever I try and cloud save, it keeps saying there is something wrong with my script and i only have 2 scripts but they are both correct and I'm so confused someone please help.

languid spire
shell herald
#

so i have to do GetAxisRaw("name") >= 1) to get it to trigger every time a button under that axis is pressed

#

yep, works

rare basin
#

would be simplier to just use the new input system

queen adder
#

Yeah tbh

#

Its so much better than the old one

#

Does need a bit of tutorials to understand it, but code monkey and samyam did some unbelievably high quality work explaining it amd showing it off

tawny cave
#

hello, I am trying to compare the position of a object at frame-1 and current frame to know if the object is moving or not. Problem is that I have an error telling me the vector2 position variable (for frame-1 position) isn't declared and it doesn't work if I declare it in public class block....

queen adder
#

Also its a bit funny how they didnt fix a typo for years now, making it so the search box doesnt work for listening for inputs

#

But the 1.8.0 pre-release packages do work now lol

wintry quarry
#

You have to declare the variable outside the method

tawny cave
#

as you can see I try to declare Vector2 lastPosition right in the public class but it doesn't work

#

I get an error in currentPosition != lastPosition

amber spruce
#

anyone know for this

buoyant knot
#

as a sidenote, your speed should probably be declared as:
[field: SerializeField] public float speed {get; private set;} = 3f;

teal viper
wintry quarry
teal viper
#

Maybe share the whole code.

buoyant knot
#

serialize field makes it appear in inspector. public lets other classes see it. private set stops other classes from modifying your speed. =3f makes the default value in inspector 3 (or whatever) when you make a new component

tawny cave
buoyant knot
#

lastPostion = ….

wintry quarry
#

You don't need to repeat the type every time you assign the variable

buoyant knot
#

Vector2 lastPosition declares a whole new variable, also named lastPosition

wintry quarry
#

That creates a new variable

buoyant knot
#

and no, the IDE will see that and just let you do that

#

because it assumes you know what you’re doing

#

because you can totally declare something like:
public MyClass(float variable) {
this.variable = variable;
}
So you can make methods where the argument has the same name as one of your class fields

#

btw another other common option to declare a variable is:
[SerializeField] private float speed;
This makes speed only accessible within this class, but makes it appear in inspector (and saves the value)

tawny cave
wintry quarry
buoyant knot
#

that doesn’t make sense

wintry quarry
#

I only told you to remove the beginning of the line

#

Leave the rest alone

#

BTW you can just do lastPosition = transform.position;

buoyant knot
#

you are trying to assign lastPosition to be a new instance of a Vector2, created with its constructor

wintry quarry
#

You don't need to be crafting the thing from scratch in the first place

tawny cave
wintry quarry
#

Try it

#

It converts automatically

buoyant knot
#

Vector3 and Vector2 can be cast into each other

#

this is an implicit cast. Since lastPosition is a Vector2, and you are trying to assign a Vector3, the program searches for an implicit cast of vector3 to Vector2

#

other classes require explicit cast. Which requires something like: lastPosition = (Vector2) transform.position;
(if that were an explicit cast)

balmy sky
#
private PlayerControls playerControls;
    private void Awake()
    {
        playerControls = new PlayerControls();
    }
    private void  Start()
    {
        playerControls.Inventory.Keyboard.performed += ctx =>ToggleAactiveSlot((int)ctx.ReadValue<float>());
    }
    private void OnEnable()
    {
        playerControls.Enable();
    }
    private void ToggleAactiveSlot (int numValue)
    {
        Debug.Log(numValue);
    }
balmy sky
wintry quarry
#

You've assigned alt keys basically, not other values

#

You should just make 4 separate actions and assign each to an individual key

balmy sky
queen adder
#

Why would you want to overcomplicate it this much?

wintry quarry
#

It will take you 2 minutes

queen adder
#

KISS (Keep it simple, stupid)

#

Dont hate on me, thats the acronym

swift crag
#

it's a little hard to express. you're relying on information that just happens to exist for the keys you're using (the name you get back from control.name)

#

if you want four input actions, define four input actions

#

it's like if I decided how much health an enemy gets based on what color its material has

wintry quarry
#

Anything to avoid actually explicitly spelling out intentions

topaz mortar
#

I have a a BuyItem script that sends a request to a database to remove the gold and add the item
If I do _ = BuyItem() it works perfectly in the client but it bugs in my database
if I do await BuyItem() it lags on the client and looks & feels really slow/weird
The database sometimes lags a second or two - causes items to duplicate, or multiple buys where you don't have enough gold but the gold is not substracted from database yet when you click a second time, ...
Is there any easy way to fix this? I want it to be smooth client side but work properly on the server side

buoyant knot
#

your code should depend on the inputaction that is invoked. Not on the specific key pressed. that is kind of the point of inputsystsem

ionic kelp
#

hello, when I want to build my game, it shows me an error message. Can you help me please

buoyant knot
#

because if you put this into PS5, and you are checking for pressing the 1 key, a PS5 controller doesn’t have a 1 key

balmy sky
buoyant knot
#

yes

swift crag
#

Yes. If they're completely generic actions, then just call them "Action 1", "Action 2", etc.

#

if you later decide you want to use QWER instead of 1234, you can now easily change the input bindings

buoyant knot
#

InputActionAsset lets you bind different keys to one action. So you can make a ā€œJumpā€ input action. This input action is triggered by: spacebar on keyboard, gamepad button 4, PS5 controller X button, Nintendo Switch joycon A button….

swift crag
#

and if you decide you want to use an xbox controller, you can just add a binding for controllers

buoyant knot
#

then you don’t need to code anhthing different

swift crag
#

One of the main goals of the input system is to separate bindings from actions

#

this is for an infinite runner game

buoyant knot
#

because your code just reads/subscribes to ā€œJumpā€ and not the specific gamepad button

swift crag
#

This is one case where the benefits are less obvious

balmy sky
swift crag
#

I also have at least one project where I've got something like

#

"Action 1", "Action 2", "Action 3", ...

buoyant knot
#

i would not call them like that, but that is the idea

#

like ā€œInventorySelect1ā€, ā€œInventorySelect2ā€

swift crag
#

hence the vagueness

buoyant knot
#

InputSystem listens for any keys that trigger InventorySelect1. Your code listens to InventorySelect1.

swift crag
buoyant knot
#

code no longer needs to know if you are on keyboard or xbox or a toaster

swift crag
#

we'd all be annoyed if we saw this:

public float value1;
public float value2;
public float value3;
#

just do a List<float> !

buoyant knot
#

tbf, you are assigning separate buttons on a keyboard/controller

swift crag
#

I think the tricky thing here is that this feels like numeric input

buoyant knot
#

so how the hell do you know which button on a joycon is 1 vs 3? lol

swift crag
#

e.g. letting the user type "32" or "13"

#

but it's not. you just happen to have nine actions corresponding to the 1-9 digits.

buoyant knot
#

that is right

#

make sense, segev?

swift crag
#

If the user was just typing in a number, you'd absolutely not make ten input actions for each digit

#

you'd just read keyboard input

buoyant knot
#

yes

#

agreed

#

i still have an issue with input system for several months that I never figured out

balmy sky
queen adder
buoyant knot
#

it’s an error called ā€œcontroller binding not foundā€, or something. I think the cause comes from trying to bind/unbind a virtual mouse, but it’s hard to diagnose because the error message is not useful

buoyant knot
#

the biggest mistake novice programmers make is honestly bad style

queen adder
#

bad style?

buoyant knot
#

let me see if I can pull up an example

#

this is what bad style looks like:

    var r = ((int)o << rb[(int)b])
        + ((int)o >> (4 - rb[(int)b]));

   r = r & 0b_1111;
    if (b >= 4) {
        r = (r & 0b_0101) + (r << 2 & 0b_1000) + (r >> 2 & 0b_0010);
    }
    return (Cardinal) r;
}```
#

the code is written in a way where you cannot tell wtf it does

queen adder
#

good lord

buoyant knot
#

in grad school, I once got a program to run a complex specialized instrument

#

the program was about 2000 lines long. super technical. variable names a, b, c… j, x , y z t w

#

one comment with a citation to a paper

#

i had to tell my PI ā€œthis isn’t happenning, chief. We’d need to start from scratch.ā€

#

point being, style isn’t something you learn from bro code or braexys. You learn that in school lol

queen adder
#

I mean I don't use correct snakecasing or anything like that, but my code is still readable šŸ™‚

buoyant knot
#

instructors will not put up with bad style. you will straight up fail your class if you have bad style

queen adder
#

very sad moment

ionic kelp
#

hello, when I want to build my game it gives me an error message

ionic kelp
#

Ok

gaunt ice
#

the only two things i understand it &0b1111 and if(b>=4){}, i guess it is trying to swap the Left/right up/down

ionic kelp
queen adder
#

Show us the PlayerMovement script

#

Line 1

ionic kelp
#

Ok

buoyant knot
#

same code but in proper style:

public static Cardinal RotateCardinal(Cardinal original, Rotation rotateBy) {
    Debug.Assert((int)original >= 0, "Tried to rotate a NEGATIVE cardinal value! Cardinals should be 0-15!");
    Debug.Assert((int)original < 16,"Tried to rotate a cardinal that was >15! 15 is the max for having the total # of directions!");

    // Bitshift to represent rotation. Moves all 4 cardinals into right spot in flags
    int rotated = ((int)original << rotationBit[(int)rotateBy])
        + ((int)original >> (4 - rotationBit[(int)rotateBy]));

    // Now the main 4 bits are right. Get rid of out-of-range bits.
    rotated = rotated & 0b_1111;
        
    // More bitmath. That operation above rotates by 2, so L/R are flipped. now isolate U/D and add back in
    if (rotateBy >= Rotation.sigma) { // Need to do a mirror plane
        rotated = (rotated & 0b_0101) + (rotated << 2 & 0b_1000) + (rotated >> 2 & 0b_0010);
    }

    return (Cardinal) rotated;
}```
ionic kelp
#

Here ?

rare basin
#

thats not how you share code

#

!code

eternal falconBOT
rare basin
buoyant knot
rare basin
queen adder
rare basin
#

either delete it if you are not using that namespace

#

or add preprocessor directives

#

#if UNITY_EDITOR

buoyant knot
#

btw, the code I posted was just for demo purposes. To show good vs bad style. not because i needed help with it.

cosmic dagger
tawny cave
#

so I am still trying to check if an object is moving by comparing its position at frame and frame-1, here is my code but it still doesn't work because "currentPosition" always has the same value of "lastPosition"

buoyant knot
eternal falconBOT
rare basin
#

in the same frame

tawny cave
# rare basin in the same frame

is there a way to save the position at frame-1 then ? I tried using the methode LateUpdate but didn't seem to work that well

cosmic dagger
tawny cave
rare basin
#

firsly, you dont need an extra variable for currentPosition

#

just use transform.position instead

#

then in the LateUpdate() i'd just do

    void LateUpdate()
    {
        if (transform.position != lastPosition)
        {
            Debug.Log("Object is moving");
        }
        else
        {
            Debug.Log("Object is not moving");
        }

        lastPosition = transform.position;
    }
buoyant knot
rare basin
#

he is not

buoyant knot
#

i’m not familiar with how character controller plays in terms of physics

rare basin
#

keep your Move() in update and in late update use the code i've pasted

buoyant knot
#

if you need last frame position, then you need to save current position right after whatever mechanism actually changes it

vital spade
#

is there a way to get like a log of what happened right before unity stopped responding and I had to manually close it through task manager?

buoyant knot
#

yes. open console

#

on mac, it is console. idk the windows equivalent

rare basin
#

unity should generate crash dump file on crashes

vital spade
buoyant knot
#

on mac, it is the system console

vital spade
rare basin
#

let me guess, infinite loop? šŸ˜„

vital spade
rare basin
#

stackoverflow exception?

vital spade
#

honestly I don't know what's causing the crash but I'll report back when I find out šŸ˜„

rare basin
#

90% of the cases are infinite loops freezing the entire editor and sometimes PC aswell lol

buoyant knot
#

if you have a stack overflow, unity will instantly crash and close. If unity freezes, that might be an infinite loop, and idk if you can see that on an editor log

teal viper
gaunt ice
#

freeze doesnt generate editor log

vital spade
#

hmm, how could I find out what's wrong then

teal viper
#

With a debugger

buoyant knot
#

but when you say freeze, the whole thing stays open, but stops responding, right?

teal viper
#

Technically, your app is still running. It's just not doing anything productive.

buoyant knot
#

ok, infinite loop i bet

vital spade
#

I'll go through the code again maybe post it here if I can't find it myself

buoyant knot
#

first thing to check are any while loops or recursive calls you added recently

#

then add an emergency escape loop count

teal viper
#

The fastest way to debug would be to cause the freeze and break with a debugger during it.

buoyant knot
#

int interations = 0;

if (iterations > 100000) {
Debug.LogError(ā€œFatal error. infinite loop.ā€);
break;
}

vital spade
buoyant knot
#

both while loops AND recursive calls are common culprits.

#

but with infinite recursion, you’d probably hit stack overflow

vital spade
#

yp it was a loop

#

!code

eternal falconBOT
wintry quarry
vital spade
#
        for (int i = 0; i < enemyPrefabs.Length; i++)
        {
            GameObject enemyPrefab = enemyPrefabs[i];
            int count = enemyCounts[i];

            for (int j = 0; j < count; j++)
            {
                Vector3 randomPosition;
                RaycastHit2D hit;

                do
                {
                    randomPosition = GetRandomPositionFromCamera();
                    hit = Physics2D.Raycast(randomPosition, Vector2.zero, Mathf.Infinity, enemySpawnLayer);
                } while (!hit.collider);

                GameObject enemy = Instantiate(enemyPrefab, randomPosition, Quaternion.identity);
                enemiesInLevel.Add(enemy);
                Debug.Log("Spawned an enemy");
            }
        }

this loop specifically if anyone was wondering, I forgot to create an enemyspawnarea in the boss room.

rare basin
#

that looks like a terrible architecture

vital spade
#

well this is the beginner's chat after all I don't claim to be an expert

rare basin
#

loop inside a loop inside another loop

#

you should avoid nested loops

#

loop in a loop

#

but double nested loops are damn.. šŸ˜„

buoyant knot
#

you should especially avoid a nested while loop

#

nested for loops are ok, but you need to be in control because the amount of calls grows quadratically

cosmic dagger
#

wow, never seen those before . . .

vital spade
#

this spesific loops gets called like twice in the whole game therefore I was not too worried

swift crag
buoyant knot
#

i have several in my codep

swift crag
#

or that never terminates!

buoyant knot
#

yes, that is a major hazard

swift crag
#
                do
                {
                    randomPosition = GetRandomPositionFromCamera();
                    hit = Physics2D.Raycast(randomPosition, Vector2.zero, Mathf.Infinity, enemySpawnLayer);
                } while (!hit.collider);
rare basin
#

gambling

swift crag
#

There is nothing stopping this from running forever.

#

It's also hard to reason about how long it will run for.

rare basin
#

if you are making an enemy spawner, If I was you I'd try to make it from scratch, avoiding nested loops

buoyant knot
#

i do have nested for loops. Like, if I need to search a tilemap for all instances of tile t, then I need to go: for (x in range) for (y in range)

swift crag
#

I wouldn't say that nested loops are a problem at all here

vital spade
swift crag
#

you can have a five layer bean dip of for loops and it'll just be slow (assuming each loop runs many times)

swift crag
#

it makes perfect sense to do a double for loop here

rare basin
#

but i dont see a reason to make them for spawning enemies (as long as it is not grid-spawning system etc)

swift crag
#

for each enemy spawner, do:

for each enemy to spawn, do:

find a spot

#

That's completely normal.

#

I think your problem is that "find a spot" can fail to terminate

static cedar
#

Fun tip: try stack allocing stuff inside a loop.

nimble scaffold
#

Is photon the only best multiplayer networking system? Is it better than fishnet?

rare basin
vital spade
swift crag
#

I'm just describing what your algorithm is doing

nimble scaffold
#

Hey @rare basin in order to do a system that my gamemode can max handle 10 players do I need to to configure room manager script?? I'm using photon

vital spade
#

well i think what happened last time is the find a spot did not terminate because there was no spot therefore unity froze

rare basin
swift crag
#

I would suggest having it give up after a certain number of tries

nimble scaffold
buoyant knot
#

i also have another nested set of for loops to iterate over all my assets. I have Wheels with lists of Family, which have lists of ObjBase, which have lists of alternate ObjBase, and each ObjBase can have multiple tiles.
My TileDirectoryClass has a big loop that goes:
foreach (wheel)
foreach (family in wheel)
foreach (objBase in family)
AddBase(objBase);
foreach(altBase in objBase) AddBase(altBase);

AddBase(objBase) {
foreach (tile in objBase) {
add tile to directory
}

vital spade
rare basin
buoyant knot
#

that is 5 layers of nesting

swift crag
#

you could use another for loop, really

eternal falconBOT
buoyant knot
nimble scaffold
#

Okk

swift crag
#

bool spawned = false;

for (int try = 0; try < 10; ++try) {
  // try to spawn
  if (itWorked) {
    spawned = true;
    break;
  }
}
#

extreme pseudocode action

nimble scaffold
vital spade
buoyant knot
#

point being, my 5 layers of nested loops works fine because I’m in total control. I know exactly how many iterations the innermost nested part of the loop needs to run. I know it’s finite, and small enough to finish everything in the blink of an eye

#

the layering of lists in lists in lists is just for organizational purposes

swift crag
#

yes, n^5 is okay if n is small

#

or if most of the loops only run a small number of times

#

in this case, the nesting is irrelevant

buoyant knot
#

it’s not really n^5. Total iterations is locked. So the number of layers of nesting could be 1-100, and it doesn’t matter

swift crag
#

it's n^5 with a small value of n

#

or maybe O(abcde) with small values for a-e

buoyant knot
#

it’s actually O(totalTiles)

swift crag
buoyant knot
#

yes

swift crag
#

it's that the innermost loop runs forever

swift crag
#

po-tay-to po-tah-to

#

my point is that you should analyze this exactly like you would any other algorithm

buoyant knot
#

I mean I have a fixed number of tiles. then i put them into wheels/family/objBase etc to organize them. So exactly how i choose to split them up is irrelevant

swift crag
#

it's not "different" because the numbers are fixed

buoyant knot
#

because the loop is built backwards, in a sense

swift crag
#

you know it's fine because you know how many tiles you have

#

you don't have to think about all of the other factors

#

that's fair

buoyant knot
#

exactly

#

and I know that whole thing runs once at the very start of the game. so performance cost is de minimus

red kindle
#

is this correct place to ask for guide with 0 hours in coding? šŸ˜„

wintry quarry
buoyant knot
#

you want some amount of experience first, or you won’t understand our help

#

you can be learning, but it doesn’t help if you have never coded at all

#

because then we’d be doing it for you entirely, and that’s not how we roll

red kindle
wintry quarry
#

it's good enough

buoyant knot
#

i would try learning basic programming first tho, tbh

#

fundamentals are important

tawny cave
buoyant knot
#

like learning to speak spanish before becoming a telemarketer in Spain

buoyant knot
#

most intro programming courses teach python, because it is very beginner friendly

#

good starting point

red kindle
#

thanks man I will ask you guys when I meet my first wall

tawny cave
#

is there a transform method to rotate an object by 180° ? (like just make it look backwards)

rare basin
#

transform.Rotate might work

#

depends on what do you want to achieve

#

instant rotation or smooth etc

slender path
#

Does anyone have a good recomendation on making an inventory system that is kinda like minecrafts?

buoyant knot
#

transform.rotation = Quaternion.Rotate(….) * transform.rotation;

#

something like that

swift crag
#

might want the other way around

#

actually, does that matter here? i remain fuzzy on this

buoyant knot
#

i expect quaternion multiplication to not be commutative

swift crag
#

yeah, it applies the lhs, then the rhs

#

I need to get a better handle on that

buoyant knot
#

rotation operators are not hard to deal with as long as you don’t need to get into the weeds, and remember they aren’t commutative

swift crag
#

yeah, I just want to have a better intuition for what happens if I, say, switch them around

buoyant knot
#

imagine a cat. head to tail is X axis. top to bottom is Y axis. left to right is Z axis.

#

Rotate by 90 degrees, X then Y. vs Y then X

swift crag
#

oh yeah

#

the cat winds up with a different orientation

buoyant knot
#

that’s how my physical chemistry professor explained it to me

#

and the difference is the commutator

#

the commutator for that is Z rotation

#

at least that is what i remember

shell herald
swift crag
#

what about it?

swift crag
# shell herald

i should point out that this is the old input system you're using here

swift crag
#

If you're using the old system (i.e. you aren't using the Input System package), you'll need to do something different

shell herald
#

i switched to the new one

swift crag
#

okay, so what is the problem?

shell herald
#

right now, i get what is plugged in, but i want to get the last input. because even if i input with my controller, it still debugs the keyboard

swift crag
#

ah, I imagine that devices is just a list of all available devices

queen adder
#

hi my visual studio code does not have the list of unity functions after i do rb.

swift crag
#

have you followed the steps in !ide ?

eternal falconBOT
rare basin
#

iirc there is InputSystem.current

#

and you can just check if current is Keyboard etc

swift crag
#

nope -- maybe you're thinking of stuff like Mouse.current

rare basin
#

hmm maybe šŸ˜„

swift crag
#

I use control schemes in one of my games to decide which input hints to display

queen adder
swift crag
#

I subscribe to InputUser.onChange

#
InputUser.onChange += OnInputUserChange;
rare basin
#

you can use the OnActionChange calblack

#

yea exactly

swift crag
#
    void OnInputUserChange(InputUser user, InputUserChange change, InputDevice device)
    {
        if (user.id == playerInput.user.id && change == InputUserChange.ControlSchemeChanged)
        {
            SetControl();
        }
    }
#

this is from a class that displays an input icon

rare basin
#

i saw this in Code Monkey's video about virtual mouse

swift crag
#

hey, I can get rid of that TODO!

#

you can ignore most of the SetControl method.

#

I use InputBinding.MaskByGroup to filter bindings by control scheme

rare basin
#

tyvm

swift crag
#

since I'm using control schemes

#

It sounds like you just need to know what kind of device is being used, so most of this is irrelevant, actually, lol

swift crag
#

Although I am a little unsure what device will be here!

#

since I'll have both mouse and keyboard devices in use

shell herald
#

thx

swift crag
# queen adder yes

show me screenshots of:

  • the External Tools settings
  • the package manager "In Project" list
swift crag
# shell herald thx

Do you need to know whether a keyboard or gamepad caused an action to run?

#

Or do you need to know when the user switches from keyboard to gamepad input?

shell herald
swift crag
#

I would suggest creating control schemes and assigning your actions to them

#

Then you can just check user.controlScheme.Value.name to see which scheme they're using

queen adder
#

@swift crag is it this?

swift crag
#

Yes, and that looks good

#

Visual Studio Editor is up to date

#

Close VSCode, then double click a script asset to reopen it

queen adder
#

im getting this, does this mean anything

queen adder
#

ngl im probs gonna just delete and use microsofts version of visual studio instead

#

its fine

slender path
#

Does anyone have a good recomendation on making an inventory system that is kinda like minecrafts?

swift crag
#

There is an extension called ".NET Install Tool" that's supposed to automatically download the software you need

#

For some people, it doesn't work. Mysterious.

#

You should be able to just hit "Get the SDK" and install .NET yourself

queen adder
#

yeah i installed it, probs not in the right place though because it didnt work

swift crag
#

you'll need to restart VSCode at the least, and probably your computer too

signal cosmos
#

to make a type of 2D controller for a character similar to the game Hollow Knight, how should I do it professionally,Give me concrete advice, what should I use?

swift crag
#

tbh, I'd say to just try it. Do it several ways -- both kinematic and non kinematic rigidbodies

#

Make small games (maybe look for game jams to do) with very different platforming mechanics

rich adder
swift crag
#

you want to make your game feel as fair as possible, so learn about things like "coyote time" (letting the player jump for a brief moment after going off a ledge)

queen adder
#

restarted pc

#

but still same problem

swift crag
# queen adder

This is the extension that downloads the SDK, not the SDK

queen adder
#

oh

swift crag
#

did you click "Get the SDK"

queen adder
#

yes

#

and installed it

swift crag
#

show me what you installed

queen adder
rich adder
#

download 7

#

8.0 is still not full release

swift crag
#

ah, yes, I should have specified

queen adder
#

ok 1 sec

#

installed this

#

restarted everything

#

still wont autocomplete any unity code

#

@swift crag thanks for ur help but i am just getting the purple version instead

#

i give up

rich adder
queen adder
#

no

#

il try that

swift crag
#

give that a whack, yeah

queen adder
#

that worked

#

thanks

rich adder
#

woo

queen adder
#

been stuck on this for like days, been youtubing and googling and you guys solve it super fast

#

thank u!

dull eagle
#

Hey guys, is there a way to stop the checkmark from disappearing whenever the toggle "Is On" property is false? Would like to instead change it to a different image.

rare basin
#

wdym

rich adder
#

even though I still use VS

wintry quarry
dull eagle
queen adder
# queen adder that worked

Usually when i have a no unity code problem in vs, if i go to Asset>Open C# project, instead of clicking on scripts or right click open, it works fine

#

Glad you got it working tho

wintry quarry
humble lantern
#

Hey can you see why percHit may be 0? I have the Code and what the Debug line gave me. Both Input numbers are in int and the output is specifically declared a float but its just returning 0 instead of 0,75.

polar acorn
#

(float) amount / (float) MAX_HEALTH

humble lantern
#

ohh thank you

buoyant knot
#

3 / 2 = 1

humble lantern
#

because it rounds, alright

buoyant knot
#

integer division is defined that way, to always output an int

#

1.5 is not an int, so no matter how it does it, you will never get 1.5

humble lantern
#

is there a similarly easy to miss reason why my slider always has double the value it was supposed to get? it was supposed to get its current value - 0,75 but instead it got its current vallue -1,5 which means it ended up being -0,5 and not 0,25

buoyant knot
#

so most int division gives the same result as rounding down

humble lantern
#

image set to fill* not slider

dull eagle
eager elm
dull eagle
#

@eager elm The checkmark is always active, whenever the "Is On" is set to false it just changes the graphic alpha to 0

fickle karma
#

Hello i have these 2 scripts, and currently im only able to move the gameobject which i put into my inspector. I need to achieve a functionality where when a gameobject is clicked i can move the object clicked, and not the one in the inspector. By adding a static variable or other stuff, i just destroy the already achieved functionality. Im not good enough to add this on my own.

https://paste.mod.gg/ahrkeqofsuet/0
https://paste.mod.gg/qupcikcckvtp/0

queen adder
#

how do i fix this

#

im tryna make flappybird

polar acorn
#

Semicolon means "end of line"

#

So there's nothing in your SpawnPipe function

swift crag
#

it terminates the statement, yes

#

It's exactly the same kind of error as this:

#
if (false);
  Debug.Log("I shouldn't run!");
#

this is equivalent to...

#
if (false)
{

}
Debug.Log("I shouldn't run!");
queen adder
swift crag
swift crag
polar acorn
swift crag
#

You ended the definition with that semicolon.

queen adder
#

ahhhh

#

i see

#

thank you

red kindle
#

okay so first trouble

I get an error when I edit my script in visual studio and it does not find same commands as the tutorial video does

The error code is CS1002 ;expected

polar acorn
slender path
#

so i am trying to make a button have a listner but am adding it via code. does anyone know how to add the object to it?

red kindle
polar acorn
eternal falconBOT
slender path
#

so i am trying to make a button have a listner but am adding it via code. does anyone know how to add the object to it?

red kindle
slender path
polar acorn
slender path
wintry quarry
red kindle
polar acorn
red kindle
eager elm
polar acorn
#

If it's not underlined in your IDE, you need to configure it. !ide

eternal falconBOT
humble lantern
#

hey since I cant find a clear answer online, is there a simple way to get the length of an animation clip using its name?

rich adder
polar acorn
dull eagle
humble lantern
#

zamn

slender path
polar acorn
# slender path

That function has a parameter, so it does not fit the built in delegate. Even optional, it still has one. You should make an overload that has no parameters, and one with a defined item

slender path
#

ok

humble lantern
languid spire
slender path
polar acorn
#

Use logs to check if it's running

slender path
polar acorn
polar acorn
# slender path

So, you aren't getting the "CLICK" message when you click on it?

polar acorn
# slender path nope

Try putting in another function manually in the inspector and see if that one logs, to see if your button is working at all

tawny cave
#

how do I create a quaternion that is looking in the forward direction of an object, and another quaternion looking in the backward direction of that same object ?

boreal tangle
#

Does someone know a good tutorial for a state machine

slender path
shell herald
#

in me not really understanding and being confused, i watched through some yt videos and came up with this, however its not really working. even if i dont use the gamepad, i can only get a "controller" debug message. https://hastebin.com/share/galequpalo.csharp what did i do wrong or not understand?

polar acorn
swift crag
tawny cave
swift crag
#

transform.forward and -transform.forward

#

since there's no transform.back

#

you should also pass transform.up as the second argument

#

Quaternion.LookRotation(transform.forward, transform.up) for example

#

The second argument determines which direction is "up" for the resulting rotation

wintry quarry
#

this will be the same as Quaternion.LookRotation(transform.forward, transform.up)

tawny cave
swift crag
#

I would not say that.

polar acorn
#

You need two directions to define an orientation

swift crag
#

if you do Quaternion.LookRotation(Vector3.forward, Vector3.right), the resulting rotation will:

  • point in the forwards direction
  • be rolled 90 degrees to the right
tawny cave
#

ok makes more sens ^^

#

I just have a syntaxe error preventing me from doing the thing tho :/

balmy sky
rare basin
#

Rotate is a function

#

you cant use it as a variable

balmy sky
# balmy sky Hey Fen, sorry for the delay ,but is that what u guys were meaning ? i did cre...
public class ActiveInventory : MonoBehaviour
{
    private int activeSlotIndexNum= 0;
    private PlayerControls playerControls;
    private void Awake()
    {
        playerControls = new PlayerControls();
    }
    private void  Start()
    {
        playerControls.Inventory.Keyboard1.performed += ctx => ToggleActiveHighlight(0);
        playerControls.Inventory.Keyboard2.performed += ctx => ToggleActiveHighlight(1);
        playerControls.Inventory.Keyboard3.performed += ctx => ToggleActiveHighlight(2);
        playerControls.Inventory.Keyboard4.performed += ctx => ToggleActiveHighlight(3);
        playerControls.Inventory.Keyboard5.performed += ctx => ToggleActiveHighlight(4);

    }
    private void OnEnable()
    {
        playerControls.Enable();
    }
    private void ToggleActiveHighlight(int indexNum)
    {
        activeSlotIndexNum = indexNum;
    
    foreach (Transform inventorySlot in this.transform)
    {
        inventorySlot.GetChild(0).gameObject.SetActive(false);
    }
    this.transform.GetChild(indexNum).GetChild(0).gameObject.SetActive(true);
    }

}
rare basin
#

you can't assign anything to a function, it doesnt make sense

swift crag
#

I guess you could make a List<InputActionReference>.

#

and then iterate over it

balmy sky
swift crag
#

InputActionReference lets you reference a specific input action

balmy sky
plush zealot
#

I'm using this Script to controll a third player character, the character is supposed to turn into the camera's direction on a movement input while the camera is able to look around freely. Unfortunately it's not working as intended, even tho I followed a tutorial on it and double checked the script multiple times, any help appreciated.

using System.Collections.Generic;
using UnityEngine;

public class third_player_movement : MonoBehaviour
{
    public CharacterController controller;
    public float speed = 6F;
    float turnSmoothVelocity;
    float turnSmoothTime = 0.1f;
    public Transform camera;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

        if(direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + camera.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            controller.Move(moveDir.normalized * speed * Time.deltaTime);
        }
    }
}```
swift crag
#

so what is your problem?

#

you haven't described a problem.

plush zealot
#

it didnt change rotation

#

on input

#

but i found the issue

#

i forgot to

#

refrence what transform to rotate

#

lol

#

has to be "controller.transform.rotation" in the 7th to last line

vale blade
#

Is there a clean way to serialize dictionaries in the inspector?

#

right now I'm using a custom class

wintry quarry
vale blade
# wintry quarry Use a premade SerializableDictionary solution or just serialize a list of key/va...

yeah that's kind of what I'm doing now, creating a warpper SerializableDict class like so

[Serializable]
public class SerializableDictionary<TKey, TValue>
{
    [SerializeField] private List<SerializableKeyValuePair<TKey, TValue>> _contents;

    private Dictionary<TKey, TValue> _dictionary;
   
    private Dictionary<TKey, TValue> Dictionary
    {
        get
        {
            _dictionary ??= InitializeDictionary();
            return _dictionary;
        }
    }
    
    public bool TryGetValue(TKey key, out TValue value)
    {
        return Dictionary.TryGetValue(key, out value);
    }

    private Dictionary<TKey, TValue> InitializeDictionary()
    {
        return _contents.ToDictionary(keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value);
    }
}
swift crag
#

especially if the data doesn't change at runtime

#

The problem with making a List<KeyValueStruct> and making a dict out of it in Awake is that the dict won't update if you mess with the list

#

it's also annoying if you need to access that data in editor scripts

#

i ran into that yesterday

wintry quarry
swift crag
#

i decided to just keep the list and search it every time 🫠

swift crag
#

(the list has at most six things in it, so whatever)

vale blade
wintry quarry
swift crag
#

i'm not kicking this anthill more than I have to :p

tiny hawk
#

When resolving merge conflicts for things like File ids, is it better to go with the source code, base code, or destination code?

red kindle
#

How do I type decimals in VS?

languid spire
#

4.81f

balmy sky
# swift crag `InputActionReference` lets you reference a specific input action
[SerializeField] List<InputActionReference> inputActionReferences = new List<InputActionReference>();
    private void  Start()
    {
        for (int i = 0; i < inputActionReferences.Count; i++)
        {
            playerControls.Inventory.inputActionReferences[i].performed += ctx => ToggleActiveHighlight(i);
        }
           
    }
``` getting "PlayerControls.InventoryActions' does not contain a definition for 'inputActionReferences" error , any idea why ?
swift crag
#

you probably forgot to delete playerControls.Inventory off the front

#

also, you'll want to do inputActionReference[i].action.performed

#

InputActionReference lets you reference a specific input action. The outcome is the same as getting the InputAction from that playerControls object

#

i presume that's the generated C# class

vale blade
#

I'm working on this game where I have NPC's that are powered by ChatGPT, and I want to have prompts in which I can parse bits of other prompts.
I feel like I'm switching data structures every day lmao

For now I settled on a solution where I can parse certain properties from scriptable objects into a prompt.
I'm going slightly insane though, asyou can misspell the token identifiers in the prompt and then stuff just breaks, so you have to be very precise.

No idea what a better solution for this would be haha

#

I mean it's not terrible but tomorrow I'll wake up and want to refactor it all again haha

short hazel
balmy sky
swift crag
#

show me the error.

#

along with your current code.

balmy sky
# swift crag show me the error.
[SerializeField] List<InputActionReference> inputActionReferences = new List<InputActionReference>();
    private void  Start()
    {
        for (int i = 0; i < inputActionReferences.Count; i++)
        {
            inputActionReferences[i].action.performed += ctx => ToggleActiveHighlight(i);
        }
           
    }
    private void OnEnable()
    {
        playerControls.Enable();
    }
    private void ToggleActiveHighlight(int indexNum)
    {
        activeSlotIndexNum = indexNum;
    
    foreach (Transform inventorySlot in this.transform)
    {
        inventorySlot.GetChild(0).gameObject.SetActive(false);
    }
    this.transform.GetChild(indexNum).GetChild(0).gameObject.SetActive(true);
        Debug.Log(indexNum);
    }
swift crag
#

and where is that error coming from?

#

see the stack trace

#

I'm suspicious of that ToggleActiveHighlight code

balmy sky
swift crag
#

oh, this is just the inspector having a fit

#

it's trying to find a property that doesn't exist, for some reason

#

restarting the editor generally cleanses these demons

#

cleanses, exorcizes, whatever

balmy sky
#

lol ill try

loud topaz
#

I created an animation state in the Unity Editor but its missing in the Controller File, but why?

#

nothing fancy

swift crag
#

Hit "Save Project" in the file menu

#

see if the file changes

#

ctrl-S saves the open scene. I'm a little unclear on what actually triggers non-scene assets to be saved.

#

I've never had a problem with them not saving...

balmy sky
loud topaz
#

nevermind works like a charm. saved the unity file. feeling stupid.

swift crag
#

This shouldn't be necessary

#

since you're already doing playerControls.Enable(), which will enable those input actinos

#

But I've never really used the generated C# class option

shell herald
#

bump

swift crag
#

"transform child out of bounds" means you asked for a bogus child index

spiral oak
#

Hi, I have offered myself to a studio to program a inventory system for their game, but Im a bit nervous. So, could I show you the code structure (just name ans describe the classes and interfaces) Ive devised so that you can opine if its good? Or this channel is only for issues?

#

I know, "dont ask to ask", but Im not sure if I can ask that in this channel

eternal needle
loud topaz
#

Unity should show an asterisk at the top when changing something in animation controller.

rich adder
#

Animator Controller is its own asset

swift crag
#

Some assets do show that they're unsaved.

rich adder
#

true yeah some custom SO do it

spiral oak
buoyant knot
#

the first step in writing a program is figuring out what you need it to do.

swift crag
#

inventories are a common source of Design Problems (tm)

buoyant knot
#

you need to ask more questions before you do any coding

swift crag
#

they're complex

#

get more information and whiteboard how it'll work

buoyant knot
#

they aren my that complex, but you really need to clearly define the constraints early on

loud topaz
buoyant knot
#

because changing the constraints later might require you to start from scratch

swift crag
#

you often have several kinds of data mashed together into the inventory

#

weapons, items, key items...

#

some things can share behaviors and some can't

#

it gets gross

spiral oak
#

At least, for now I want to make a little prototype

eternal needle
swift crag
#

are all items similar, or are there different kinds of items that need vastly different treatment?

spiral oak
eternal needle
#

I ran into some problems making an inventory already and it's gotta somewhat be remade. It really is important to know what you want first. In mine, everything inventory related somehow became a dictionary holding different data

eternal needle
spiral oak
balmy sky
swift crag
#

Maybe do some logging.

#

Are you off by one now?

#

Maybe you used to do 1-4 instead of 0-3

keen dew
#

i is in a closure so it's always off by one. Should be

for (int i = 0; i < inputActionReferences.Count; i++)
{
    int index = i;
    inputActionReferences[i].action.performed += ctx => ToggleActiveHighlight(index);
}
balmy sky
short hazel
balmy sky
#

@swift crag @keen dew ty so much!! ill restrain from spamming this channel for today at least xD u guys are amazing

buoyant knot
heady coyote
#

I have the canvas shown below in my project. My goal is to be able to change the source image of "Image" to one of 7 possible images during runtime. Does anyone know how I could achieve this?

rich adder
wintry quarry
#

This^ but it's assuming you want a random one. The imageComp.sprite = someSprite; part is the most important bit. The rest depends on how you want to choose which one. to set it to

heady coyote
rich adder
#

if you want a specific one just use the index of it

#

myImages[3] - this one gives 4th one for example

#

(assuming you want to keep them in a list of 7 sprites)

wintry quarry
heady coyote
graceful citrus
#
    private void Update()
    {
        float translationfb = Input.GetAxis("Vertical") * thrust * Time.deltaTime;
        float translationlr = Input.GetAxis("Horizontal") * thrust * Time.deltaTime;

        ri.AddForce(transform.forward * translationfb, ForceMode.Force);
        ri.AddForce(transform.right * translationlr, ForceMode.Force);

        rotationX += Input.GetAxis("Mouse X") * sensitivity;
        rotationY += Input.GetAxis("Mouse Y") * -1 * sensitivity;
        cam.transform.rotation = Quaternion.Euler(Mathf.Clamp(rotationY, -80, 80), rotationX, 0); ;
        transform.rotation = Quaternion.Euler(0, rotationX, 0);
    }

this code is making the movement considerably more jittery than i expected. why is it doing this?

wintry quarry
polar acorn
graceful citrus
heady coyote
wintry quarry
graceful citrus
#

ahh i see

#

yeah you right you right

rich adder
graceful citrus
#

idk how i forgot that lmao

wintry quarry
#

you can do the rotation here via rb.rotation if you wish, that part should be ok assuming it's simple y axis rotation on an upright capsule

polar acorn
graceful citrus
#

so i rotate rigidbody? not transform?

wintry quarry
graceful citrus
#

do i do the camera rotation in fixedupdate too?

#

or does that stay in update

wintry quarry
#

no

#

neither

#

neither rotation needs to go in fixedupdate

#

only the force

#

Also Time.deltaTime should not be multiplied into the force calculation either

graceful citrus
#

wuh?

#

why not?

wintry quarry
#

because it doesn't make any sense

#

Time.fixedDeltaTime is already incorporated into the default ForceMode for AddForce

graceful citrus
#

oh sick

wintry quarry
#

and you'll be calling it in FixedUpdate, so everything will line up

graceful citrus
#

rightttt

#

i forgot how helpful unity is lmao

#

movement still seems rather jittery tho

stuck palm
#

is there a way to get a list of PlayerInputs that have joined?

copper perch
#

Bad news today Glock US Legal department said I cannot use a glock gun in my game.
I spent all that time making the glocks and animating them, making sure they were commercial free from the Unity Asset store.
I tried to alter the glock, like remove bits from the main gun like the trigger and sight, to make it look different but they said it still looks too much like a glock.
Just letting you know this in case your using a copyrighted gun in your game.
But Dead Trigger 2 uses dual glocks, and so does the game Contract Wars, so I am not sure of the copyright permissions these games companies have or if they use the glocks illigally in their game.

frosty hound
#

Not sure why that has to do with coding?

copper perch
frosty hound
#

But like anything that involves an IP you have to pay for a license.

#

Again, nothing to do with coding.

rich adder
#

wait what Glock shape is trademarked?

#

tf

copper perch
#

thanks

rocky canyon
#

yup, those are 100% glocks btw

keen hinge
#

Okay so I cant get my Groundcheck Transform to appear under my scripting for the player. Any advice?

eternal falconBOT
gusty void
#

hi, just wnated to ask why im getting a nullreferenceException on my PlayerMovement ? thank you

short hazel
#

!vs

eternal falconBOT
#
Visual Studio guide

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

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

short hazel
short hazel
#

If that line is not underlined red, configure your code editor, this simplifies programming by a lot

#

!ide

eternal falconBOT
keen hinge
#

And that fixed it, tysm

queen adder
#

why does my ui game object not apear in scene view

short hazel
#

It's there, select it in the Hierarchy, move your mouse over to the Scene View and press F to focus it

queen adder
#

thank u found it

copper perch
#

In some computer games and RPGs, you get real guns with fake names. They have the appearance and the characteristics of the real gun, but not the name.

The reason appears to be avoiding potential lawsuits from the manufacturers of said firearms; it's a lot easier to prove a trademark infringement over a name than over the unique likeness of a weapon, and many companies haven't trademarked the latter anyway. There's also the issue of editorial control; much as car companies can dictate that vehicles in videogames not be shown crashing or being damaged as a requirement for licensing, gun companies could potentially demand their weapons only be shown in certain situations as a requirement for inclusion of their trademarks. Oddly, this often happens even with guns with which trademark issues wouldn't be relevant, whether because they're so old that trademarks have lapsed or because their developers went out of business.

In recent times, the likenesses of firearms have also been subject to this trope. The high level of graphical detail that modern computer games are capable of has caused some to fear that gun companies could take legal action on likenesses alone, regardless if a game uses fake names. Visual examples can range from minor embellishments to entirely fictional firearm models, the latter of which is typically done by merging visual elements from several real-life firearms into one designnote . In any case, the statistical behavior of these fictional guns are often closely modeled after real-life examples.

short hazel
#

They can't let go over the fact that you indeed cannot use intellectual property and trademarks without permission

eternal needle
short hazel
copper perch
#

šŸ¤•

short hazel
#

This is a code channel

copper perch
#

im depressed

#

sorry

short hazel
#

Can you not continue the conversation here? Thanks

hardy fox
#

@short hazel sorry to be nuisance but could you breakdown what u were trying to tell me in #archived-code-general

short hazel
#
if (enemy != null)

This checks that the enemy is not destroyed. It is essential, because without it, you get the error you're experiencing right now

short hazel
maiden current
#

I'm in my way to make a save system with JSON. I have an interface implemented in all the objects which I have to save or load data.

My problem is that I want to save or load the data from all objects who have implemented the interface, whether they are in the scene or not, I don't know how to do this. I don't know another approach besides searching the objects in the scene.

hardy fox
dry tendon
#

Does someone know a god free audioManager?

eternal needle
short hazel
#

To be sure you won't get the errors, you need to move all the code that's after the yield and that uses the enemy variable, inside of the if statement

maiden current
polar acorn
dry tendon
hardy fox
eternal needle
# maiden current <:domingochiiii:1069283152645857280>. How do I else save the data in other scene...

I really dont know what you mean, are you talking about 2 scenes loaded additively? Easiest thing imo is having the objects to save register themself with a singleton save manager, instead of trying to find the objects.
If you're talking about 2 different scenes entirely, not additively loaded, then idk what to tell you. The objects arent there, so you wont be able to save an object that isnt there

dry tendon
maiden current
eternal needle
maiden current
# eternal needle i have honestly not answered anything, I am asking you what functionality you ar...

I didn't want to be annoying with lots of questions Cat_catcry_retrasados . What I meant with the worlds analogy is that I have let's say a town and a dungeon in different scenes. If I interact with an NPC in the town that leads to a change in the map and I later go to the dungeon and save the game there...

When I load the game again I want to load the changes made in the town scene too. I know I have to do a DontDestroy GameObject with an static class that holds...

Nevermind I just figured out while writing this what to do with the persistent class

#

I wasn't understanding but now I do mehachad

#

me and GPT 3.5 what could go wrong

rocky canyon
#

lol, nothing that ur aware of šŸ˜„

swift crag
#

when you quit the game, you serialize it to disk, and when you relaunch the game, you deserialize it

#

I'm figuring this out myself for a Soulslike game.

stuck palm
#

im using the player input manager, and when i load a scene the data doesnt get reset

swift crag
#

where does the player input manager component exist?

stuck palm
hardy fox
#

why is the word coins not appearing?

swift crag
#

Is the object you have selected right now a child of the canvas?

hardy fox
#

no

swift crag
#

UI text needs to be a child of a canvas.

#

(or a grandchild; it just has to have a canvas as one of its parents)

hardy fox
#

ah okay

#

having another error

swift crag
#

What is line 33?

hardy fox
loud topaz
#

Question: How do i make that work? The idea was a Platform, where the Players gets attached to, to move with it. After Exiting the Trigger unparents the Player. Problem: The Player changes its Size and stuff when i set the wordPositionStays to true, if false he teleports away.

swift crag
#

You generally shouldn't parent things to non-uniformly-scaled transforms. It causes headaches.

polar acorn
# hardy fox

Either enemy is null or it has no EnemyHealth component

loud topaz
#

like in blender for example

swift crag
#

Sure. Apply transforms in Blender.

#

note that the platform may still be scaled (e.g. to [100, 100, 100]) by the import process

hardy fox
swift crag
#

"Surface" would be the model

swift crag
#

so you'd better diagnose that

polar acorn
swift crag
#

The code does test enemy != null

loud topaz
#

thx ill look into it

stuck palm
polar acorn
#

There's two things in that sentence

solemn fractal
#

hey guys, my player movement is very basic. But I am afraid that when I am going in diagonal, i go faster than up, down, left and right. 2d game. here is the code: ```cs

private void PlayerMovement(){

    float horizontalInput = Input.GetAxisRaw("Horizontal");
    float verticalInput = Input.GetAxisRaw("Vertical");

    transform.Translate(Vector3.right * playerSpeed * horizontalInput * Time.deltaTime);
    transform.Translate(Vector3.up * playerSpeed * verticalInput * Time.deltaTime);
polar acorn
#

the word "or" is what is known as a "conjunction" to connect two independent clauses into a sentence

frosty hound
#

You need to normalize your direction prior to using it in your movement.

solemn fractal
hardy fox
#

enemyhealth

polar acorn
solemn fractal
swift crag
#

it doesn't matter what that script contains

#

GetComponent<EnemyHealth>() returns null if it can't find the component.

polar acorn
frosty hound
hardy fox
swift crag
#

That script defines a kind of component

loud topaz
#

got it working šŸ™‚ @swift crag

swift crag
#

That doesn't mean the enemy has that component

swift crag
# hardy fox

or that whatever you hit here has that component

#

You should log enemy, as well as the result of enemy.GetComponent<EnemyHealth>()

hardy fox
#

what will that do?

swift crag
#

logging enemy will show you what you're actually detecting with that physics query

polar acorn
swift crag
#

and enemy.GetComponent<EnemyHealth>() will show you if the enemy has an EnemyHealth component

polar acorn
#

the enemy object doesn't have one on it

swift crag
#

it's like if I told someone what a dog was, then expected them to automatically have a dog

hardy fox
polar acorn
#

Either drag it onto it or hit the Add Component button

swift crag
#

We'll know for sure if you just log those two things.

swift crag
#

That is an EnemyHealth component, yes.

polar acorn
#

Since the enemy object does not have one on it, then this is not the enemy object

swift crag
#

It will tell you exactly what is happening.

hardy fox
solemn fractal
# frosty hound You'll need to construct a new vector2 which is both your horizontal and vertic...

but where here I add the vector? u mean I use only 1 cs transform.Translate(vector etc..etc..) ??? ```cs
private void PlayerMovement(){

    float horizontalInput = Input.GetAxisRaw("Horizontal");
    float verticalInput = Input.GetAxisRaw("Vertical");

    Vector2 vector = new Vector2( horizontalInput, verticalInput).normalized;

    transform.Translate(Vector3.right * playerSpeed * horizontalInput * Time.deltaTime);
    transform.Translate(Vector3.up * playerSpeed * verticalInput * Time.deltaTime);```
swift crag
hardy fox
swift crag
#

Yes, Debug.Log.

polar acorn
timber tide
#

you got a direction speed and delta time

hardy fox
#

no clue where the debug.log is supposed to goawkwardsweat

tawny cave
#

I need help with this, I don't know how to make collision detection functions work. I don't even have anything showing up in the console (all I want to do is to detect if the player is in collision with a mob and teleport it to the beginning of the level). Both player and mob have a capsule collider btw

swift crag
swift crag
#

or is that another color

short hazel
#

Warnings it seemy

swift crag
#

are those inner functions, perhaps?

#

stuck inside another method

short hazel
#

Yeah probably

tawny cave
#

it says function is decalred but never used

swift crag
#

If you declare a function inside of another function, it only exists inside of the containing function

short hazel
#

Yeah, it's a local function, take it out of whatever it's in right now

swift crag
#

You need to declare these things directly inside the class.

polar acorn
hardy fox
#

think its time to give up on programmingnotlikethis

swift crag
#

log is not Log

short hazel
#

Uppercase "L"

swift crag
#

pay attention to spelling and capitalization.

short hazel
#

You will also need to debug the two things Fen told you, not some random string

hardy fox
#

is this correct?

short hazel
#

No

swift crag
#

well, no, you aren't logging the things I asked you to log.

#

but it is valid syntax

short hazel
polar acorn
timber tide
swift crag
#

also, I would suggest passing enemy as the second argument. this will let you click on the log entry to be taken to the thing you hit

#
Debug.Log(enemy, enemy);
#

like so

solemn fractal
swift crag
#

this will help if it turns out you're hitting something weird

frosty hound
hardy fox
tawny cave
swift crag
#

If you aren't clear on something, ask

polar acorn
swift crag
#

don't just do random things and then throw it back at us

timber tide
#

reminds me of some old snes games where running diagonal was busted too

hardy fox
swift crag
meager gust
hardy fox
swift crag
rocky canyon
#

you need to log the values of 'enemy' and the getcomponent..

polar acorn
rocky canyon
#

after you check if its there..

swift crag
#

this will log the enemy variable.

polar acorn
#

Debug Log should literally have been the first line of code you ever wrote in unity

#

if you don't know how to do that, then you are way ahead of yourself

rocky canyon
#

if enemy is !null -> debug.log(enemy) so u know what it is.

swift crag
#

you can pass whatever you want to Debug.Log. It will get turned into a string and written to the console.

rocky canyon
#

if enemy is null then u find out why its null

short hazel
polar acorn
rocky canyon
#

but if it aint u'll know what it is.. by using enemy.name for example to log it's name or w/e

hardy fox
rocky canyon
#

remember a variable is a container, you can log any variable to get its name, type, value, etc.. using Debug.Log()

swift crag
polar acorn
rocky canyon
#

inside the brackets.. with the rest of ur code

polar acorn
#

do not code any further

#

go into the pins

#

do the intro to C# course

rocky canyon
#

lol

polar acorn
#

and learn how to write anything

swift crag
#

if you don't understand why this has completely changed the meaning of your script, then you need to sort that out first.

polar acorn
#

You should not be coding anything yet. You are still in the "learning what words mean" phase

swift crag
#

we've spent about 15 minutes trying to get you to write two lines of code. you need more practice.

hardy fox
rocky canyon
#

yes, thas correct.. but do u know why?

#

and when, it runs

tawny cave
polar acorn
hardy fox
rocky canyon
#

ya, when the if(statement) is true

short hazel
rocky canyon
#

so its in the if statements { ... } body

tender stag
#

i just made this editor script to make the enemy field of vision

tawny cave
tender stag
#

how do i re create this through code?

#

like with a raycast

polar acorn
hardy fox
polar acorn
#

you need to actually think things through and then execute on them, not just guess until people on discord tell you it's right

short hazel
rocky canyon
#

try and see.. see what it logs.. maybe log its name.. make sure its the thing u expect it to be.

swift crag
rocky canyon
#

if it is, debug the getcomponent to see if that is what its supposed to be, etc

swift crag
#

If it's below a limit, shoot a ray and see if it hits an obstacle

tawny cave
swift crag
#

If you want that nice rectangular FOV, you'll want to test the horizontal and vertical angles separately.

meager gust
short hazel
meager gust
#

@tender stagyou don't want to shoot out 10,000 raycasts

tender stag
#

of the angle

tawny cave
hardy fox
polar acorn
short hazel
swift crag
# swift crag If you want that nice rectangular FOV, you'll want to test the horizontal and ve...

To do that, you can do something like this:

Vector3 toPlayer = player.transform.position - transform.position;
Vector3 eyeVec = transform.forward;

Vector3 verticalToPlayer = Vector3.ProjectOnPlane(toPlayer, transform.right);
Vector3 horizontalToPlayer = Vector3.ProjectOnPlane(toPlayer, transform.up);

float vertical = Vector3.Angle(eyeVec, verticalToPlayer);
float horizontal = Vector3.Angle(eyeVec, horizontalToPlayer);

ProjectOnPlane gets rid of the part of a vector that lines up with the second argument. So, the first one throws out the left-right part of the vector, and the second one throws out the up-down part of the vector.

#

(eyeVec should probably be the enemy's head transform)

#

You can think of ProjectOnPlane as "squishing" the vector into a plane whose normal is the second argument

#

so Vector3.ProjectOnPlane(transform.position, Vector3.up); gets rid of the Y component entirely, for example