#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 581 of 1

naive pawn
#

do any beginners even use ides for unreal

languid spire
#

we cannot make people read screens and think however much we would like to

naive pawn
#

actually ide packages in unity are installed when you create a new project

#

the config is done to the ide

languid spire
last edge
#

i for sure know i wont be able to make a full on rpg game haha but maybe a platformer with an inventory :3

i was messing with what unity is capable of and if you like, this is what i have so far https://2dispgame.z9.web.core.windows.net/

fringe plover
#

Doesnt work in builds ๐Ÿ’€

last edge
#

i pushed it onto azure

swift crag
rocky canyon
fringe plover
#

yes

rocky canyon
#

still just fiddling and tinkering

swift crag
#

I should've had you add an else block for GUILayout.Label("No hit.");

fringe plover
#

wait

swift crag
#

Do that to be absolutely sure that it's not just a problem with the GUI text being off-screen

fringe plover
#

no, i just redid logic for Raycasting

naive pawn
#

@last edge now that you've configured your ide, reread what osmal said ^

verbal dome
#

Props for using IMGUI for onscreen debug

#

Great tool for that IMO

swift crag
#

It's very handy

#

It's also a bit spooky -- it runs multiple times per frame

#

in this case, that doesn't matter

verbal dome
#

Yeah

craggy lake
#

whats the class for text displays?

swift crag
#

Depends on what component you're using!

craggy lake
#

(legacy and not textmeshpro)

#

simple text i think

swift crag
#

isn't it just "Text"? You can check the UI package docs

last edge
#

it works now ty osmal @verbal dome

languid spire
naive pawn
craggy lake
languid spire
craggy lake
#

alr

swift crag
last edge
languid spire
#

hasn;t changed

rocky canyon
languid spire
last edge
#

i swapped from gamer maker 2. and lets just say, this is tough not having everything just handed out to me but its fun

fringe plover
verbal dome
#

Have you tried a development build and checked for errors and such

swift crag
#

That too. That'll give you an in-game console and provide more information

fringe plover
swift crag
fringe plover
#

meant that it didnt do what i wanted in build

#

nevermind

#

something is blocking

#

its Tile in build but TileClothWasher in editor

craggy lake
#
changeTo = PlayerPrefs.GetInt("HighScore");
highScoreDisplay.text = ToString(changeTo);

any ideas why im getting an error to do with tostring taking 1 arguement

fringe plover
#

I had another collider under the washer

rocky canyon
#

changeTo.ToString();

fringe plover
#

Omfg guys im so dumb

#

thanks for helping

craggy lake
#

tysm

rocky canyon
#

np.. i think the () at the end is for Formatting

craggy lake
#

i literally just switched from learning another language where the brackets were for the thing ur changing

#

lol

verbal dome
swift crag
#

ToString(foo) tries to invoke a method named ToString, passing foo as an argument

verbal dome
#

ToString can be overridden too, it's handy for debugging

swift crag
#

It's true that your own class will have a ToString method, but it's not going to understand what to do with that foo

rocky canyon
#

ahh. i just know about the 00.00 or F2 etc

swift crag
rocky canyon
#

the basic most of the formatting stuff

swift crag
#

it's nice to be able to just ToString something and get a reasonable representation of it

#

instead of just seeing a type name

swift crag
#

you would indeed do str(foo) in python

modest harness
#

im trying to make a "on hover" effect using the 2d collider
but all the objects are placed on a grid that has grid collider so they overlap causing issues
both colliders are on separate layers, I turned off their interactions in Layer collision matrix and they are both Is Trigger
none of that worked ๐Ÿ˜ญ

swift crag
#

str is a class, and str(foo) constructs it with foo as an argument

swift crag
#

It doesn't matter if the objects' layer doesn't interact with the grid's layer

verbal dome
#

So I wrote a helper```cs

    public static string ListString<T>(this ICollection<T> list)
    {
        var text = $"({list.Count}) ";
        int i = 0;
        foreach (var item in list)
        {
            if (i > 0)  text += $", {item.ToString()}";
            else text += item.ToString();
            i++;
        }
        return text;
    }```
#

Should probably use stringbuilder for larger lists but meh it's for debugging

grand snow
#

String.Join() !

swift crag
#

I always forget how to use it

#

partially because Python does it like this

#

", ".join(blarg)

verbal dome
#

Lol

naive pawn
modest harness
verbal dome
#

The overload I use more often though, takes in a func for turning each item to a string cs public static string ListString<T>(this ICollection<T> list, Func<T, string> toStringFunc)

#

So with that I don't think I could use String.Join

grand snow
#

i only use it for debugging so i use a linq .Select() to custom to string elements firstly

verbal dome
#

Or I could do it consecutively, but not sure if beneficial

naive pawn
grand snow
#

yep what i do

verbal dome
#

Hmm so that would allocate only 1 string or what

naive pawn
#

toStringFunc would allocate at least N strings already though

languid spire
verbal dome
#

Why is this better than +

#

I guess it would make my helper method shorter, yeah

naive pawn
grand snow
#

for debugging stuff i really dont care about this stuff and += will re allocate a new string anyway

naive pawn
#

"a" + "b" + "c" + "d" allocates "ab", "abc", then "abcd"
a builder would skip straight to "abcd", removing the intermediate copying

#

presumably, join would do the same, skipping the intermediates, probably with a builder

verbal dome
#

So we are just back to this lol

naive pawn
#

well yes

#

Join would just do it for you

#

less to maintain

#

i don't think you can really get much better than a string builder

obsidian plaza
#

i just did some research on string.join and wish i knew this before doing all my stat displays in game

#

the amount of times i did string +=

final kestrel
#

So okay. I have made a little progress. My code succesfully handles player rotation. And the camera rotation works partly. In the picture is my crosshair and my lookTarget. I keep missing my lookTarget's center here and having trouble understanding why im not directly looking at its center

naive pawn
obsidian plaza
#

good to know

#

i also like how u can do it with ints

verbal dome
#

Any object, really

#

Because all objects have ToString

obsidian plaza
#

i couldnt think of a use case though

#

cause itd say weird stuff no

verbal dome
#

"Position: " + transform.position

#

For example

naive pawn
#

any class or struct can implement its own ToString

verbal dome
#

Which has its own ToString implementation

#

If it didn't, it would just print out the type's name

obsidian plaza
#

ah

#

thats what i thought it did

#

i mean the typename

#

interesting

craggy lake
#
public void saveData(data)

it says "identifier expected" on this line

#

but i have no idea whats causing the error

final kestrel
#

I think you have to specify what data's type is no?

craggy lake
#

oh, righttttt

swift crag
#

It's interpreting data as the type of the parameter

#

but then it crashes into a ) instead of finding the name of the parameter

craggy lake
#

one more thing rq,

naive pawn
craggy lake
#

oh...

#

but id taken it from a text

naive pawn
#

that's not how you turn a string into an int either

craggy lake
#

is it not toint and tostring

naive pawn
#

how is score.text defined?

naive pawn
#

anything can be turned into a string

#

not everything can be turned into an int

craggy lake
#

i see

#

says cannot convert type string to int now

naive pawn
#

what is the code now?

languid spire
swift crag
#

the C# compiler does not appreciate when you make up random function names (:

naive pawn
#

you're really not giving much info to work with here

swift crag
#

You shouldn't be converting back from a string to an int at all

#

just save the score directly

languid spire
swift crag
#

the interface is there to display information. it's not part of your game logic

polar acorn
obsidian plaza
#

i think they figured out it doesnt exist lol

ember tangle
#

having a bit of a doozy.


if (attacking) if(attackTimer.Poll()) ProjectileManager.instance.CreateProjectile(entity, target, attack); ``` debug shows what the attack is (a scriptable object)
```public void CreateProjectile(Entity source, Vector3 target, Attack attack)
{
    //makes a projectile in the pool use the arguments
    Debug.Log($"creating projectile with {attack}");
    Projectile newProjectile = cache.TakeFromCache();
    newProjectile.Halt();
    newProjectile.SetProjectile(source, target, attack);
}```
The debug in the function in question cannot see the scripatble and I get errors as if it is null.

Never ran into an error like this before...
rich ice
#

why do people always forget the cs woe

polar acorn
ember tangle
polar acorn
#

First suggestion is to check to see if you have Collapse enabled in your console

ember tangle
#

It causes other issues in the game

polar acorn
#

It doesn't actually use toString it casts

ember tangle
#

its not just in the console the entire projectile system dies

polar acorn
#

so it prints null as empty string instead of the word null

#

So, check if the console has Collapse enabled. If it does, disable it. Then you'll see the actual order of the messages

ember tangle
#

Not collapsed we're good on that one

#

the issue is the attack not getting through

polar acorn
#

Can you show a screenshot of the logs where the error occurs?

#

Oh, and another idea: Consider putting the log in the if conditions. You might be correctly logging an attack, then not calling CreateProjectile there because either attacking or attackTimer.Poll() is false

#

and then it's somewhere else that's calling CreateProjectile with a null attack

ember tangle
polar acorn
#

Yeah, that seems to be what's happening here

#

There's something else calling CreateProjectile that doesn't have a log before it

ember tangle
#

not possible

polar acorn
#

Well, the log says attack is assigned. Unless the getter for attacking or .Poll() changes that, it can't be unassigned before running that function

ember tangle
#

every single entity that makes an attack has this same set of messages in console, and only they can call the projectile manager function

grand snow
#

Why not use a debugger to solve this easily?

polar acorn
#

Or at least put the first log in the if conditions

#

so it only prints when it's actually going to try

#

But yes, breakpoint the first line of CreateProjectile, then follow the call stack up

grand snow
#

It's what debuggers are for. No point struggling with random logs if it's easy to reproduce.

ember tangle
#

Yes... ill have to learn how to use debug. Its in VisualStudio or a Unity thing?

ember tangle
#

Im seeing a lot of posts saying that this is an editor error with scriptable objects and Im trying to rule that out because everything else seems completely fine

grand snow
#

This will let you figure it out as you can inspect values and see the call stack when paused at a breakpoint

ember tangle
#

Okay so I put the debug within the if statement and it completely changed the behaviour in the game. I'm totally lost here lol

#

why would that make the attack not null?

polar acorn
naive pawn
#

why do you have if (a) if (b) c; anyways

#

do you have an else after that line or something

ember tangle
#

shorthand but I see that its not needed

ember tangle
naive pawn
#

if (a && b) is shorter thonk

ember tangle
#

yes

grand snow
#

Use the debugger and you can step through and see what it's doing.
Do fix that if statement though

ember tangle
#

Ill def learn to use the debugger

naive pawn
#

this is the typical way yes

verbal dome
#

Physics collisions/queries are pretty much the only place where you sort of need to use TryGetComponent/GetComponent

slow knot
#

heya, im tryna learn a bit about unity development, i already started scriptiong but i realize i have no startegy to debug or troubleshoot. i asked ina coding server but it turns out people who code too much develop complexes and become proffesional dickheads so im asking here

frosty hound
#

That goes both ways, lots of beginners refuse help because it's not hand-holding enough.

naive pawn
#

well can't really help without knowing what you need help with, see below

#

!ask

eternal falconBOT
#

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐Ÿ”Žโ”ƒfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696

frosty hound
#

You can start by putting Debug.Logs everywhere you want to track the state of your game.

slow knot
frosty hound
#

If you want to know why something isn't running, put logs before it to see if it prints to the console.

If statement not working? Log the values you're checking in the condition to see what they are.

Things like that.

slow knot
#

also, quick question

#

my jump function isnt working

frosty hound
#

Yes normal c# is the same used in Unity. So learning the basics would be applicable.

slow knot
#

wait ill send it her

naive pawn
#

oh god that's not gonna be quick

#

!code

eternal falconBOT
slow knot
naive pawn
slow knot
#

is it fine if i just paste the like 7 line function, that sounds complicated as hell

#

public void HandleJump()
{
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded)
{
rb.AddForce(Vector3.up * JumpForce, ForceMode.Impulse);
IsGrounded = false;
}

    }
#

its unreachable it says

#

or unused actually

#

did i write something wrong

#

'''cs
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using UnityEngine;

public class movement : MonoBehaviour
{
private bool IsGrounded = true;
public float MoveSpeed = 20f;
public float JumpForce = 20f;
private Rigidbody rb;
public Transform cameraTransform;

void Start()
{
    rb = GetComponent<Rigidbody>();
    rb.freezeRotation = true;
}
void Update()
{
    float vertical = Input.GetAxis("Vertical");
    float horizontal = Input.GetAxis("Horizontal");

    Vector3 forward = cameraTransform.forward;
    forward.y = 0;
    forward.Normalize();

    Vector3 right = cameraTransform.right;
    right.y = 0;
    right.Normalize();

    

    Vector3 moveDirection = (forward * vertical + right * horizontal).normalized;


    if (moveDirection.magnitude > 0)
    {
        rb.MovePosition(rb.position + moveDirection * MoveSpeed * Time.deltaTime);
    }
}

    public void HandleJump()
    {
        if (Input.GetKeyDown(KeyCode.Space) && IsGrounded)
    {
        rb.AddForce(Vector3.up * JumpForce, ForceMode.Impulse);
        IsGrounded = false;
    }

    }
public void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        Debug.Log("collided with ground");
        IsGrounded = true;

    }
}

}
'''

#

shit

naive pawn
#

you can copy the format from the bot embed

#

Surround code with three backquotes. Not quotation marks.

naive pawn
# eternal falcon

also, that's quite a large snippet, please use one of the paste sites. you don't need an account or anything.

slow knot
#

alrght sorry for the inconvenience

#

like this?

naive pawn
#

yes

slow knot
#

alright finally

naive pawn
#

so you never actually call HandleJump?

#

(also should probably not be public)

slow knot
#

yeah thats not supposed to bethere

#

i changed that back i swear

#

ah i didnt compile it with the changes yet

#

but that is private

#

but about the function

#

i thought it was one of those command functions things that appear sometimes. like OnCollisionEnter

naive pawn
#

methods don't get called by magic, something has to call them
Update, Start, OnCollisionEnter, and various others are messages known to unity. unity calls them when it's appropriate
but HandleJump is not something unity inherently knows about. if neither you nor unity calls that function, it's just not going to be run

slow knot
#

do i call it like i do in python by just typing the "insertname();"

naive pawn
#

yes

#

that's how functions in pretty much every language work at a simple level

slow knot
#

alright thanks a lot, lots of love and have an amazing day

toxic pine
#

whats the best way to play a particle in code

wintry quarry
#

Wdym by "the best way"?

languid spire
queen adder
#

Is luau somewhat similar to C#?

wintry quarry
#

that's about where the similarities end.

queen adder
#

Thanks. Do you know how to code in C#?

wintry quarry
#

Sure

#

lots of people do

queen adder
#

How long did it take you to understand the basic things?

naive pawn
#

mm that's quite the loaded question

wintry quarry
#

about 5 seconds

naive pawn
#

one sec

queen adder
wintry quarry
languid spire
wintry quarry
#

15 years ago ๐Ÿ˜†

naive pawn
#

(in general) there's 3 major parts to programming:

  • Language - The syntax, structure, and paradigm of each language
  • Library - The interfaces and utilities that each environment or toolset provides
  • Logic - The algorithms to do work at runtime

Logic is almost completely transferrable between each language and environment, you just have to learn the specific Language and Library that you're using
Language is also shared quite a bit between languages

of course, learning 1 part at a time is easier than learning everything at once, which is why tools like scratch or code.org are popular as coding courses for beginners, especially kids, because it only focuses on the Logic aspect

#

C# is part of the C family, so the Language aspect is really transferrable if you know another language in the family (C, C++, Java, JS/TS, etc)

wintry quarry
languid spire
#

how can logic be only 'almost completely transferable'?

naive pawn
#

the 3 L's of programming

naive pawn
#

or so ive been told

#

i don't know any fully functional languages

languid spire
wintry quarry
#

I was a Java baby

languid spire
#

child

#

'Language is also shared quite a bit between languages'
gonna love to see that at work in asm or rpg

naive pawn
#

cmon ive worded it as broadly and vaguely as i could ๐Ÿ˜ญ

#

it's targetted at beginners anyways, not like it's gonna matter at that level lol

languid spire
#

Just joshing you. Although I would guess you lost 99.9% of your intended audience with the use of the word paradigm

mortal shadow
#

i am using dotween and when i use my sliding script it makes it default to the center of the ui, how do i make it so it defaults to where it was when it was edited?

naive pawn
#

please don't crosspost

naive pawn
languid spire
hollow zenith
#

I assume it's something obvious, but I made a box 2d collider "floor" and box 2d + rigidbody2d player to add gravity:
https://i.gyazo.com/a8d7ad135b656eaf584eea22b36fc54d.png
They don't connect, even tho the player did fall down.

Any ideas why it's not pixel perfect even tho colliders aren't touching each other?

wintry quarry
hollow zenith
#

it's set to 0.01
I guess that I should leave it be and simply change my colliders to be a bit smaller so the sprite can "touch" the floor?

wintry quarry
#

or offset them a little

hollow zenith
#

By offset you mean to move the collider "inside" the sprite a bit right?(what I said above)

#

Not sure if its visible here, but I made white square collider smaller at the bottom

wintry quarry
hollow zenith
#

or rather how do I do that?
Do you mean to make a sprite with an offset in the editor?

#

with empty space under its feet?

#

I dont think that will work since the collider has to be smaller

wintry quarry
#

In the Unity editor

hollow zenith
#

oh maybe the mistake I made is to have 1 object only

#

I assume you mean to separate collider from a sprite

#

I put both on same object

#

That would definitely make sense ๐Ÿ˜„

wintry quarry
#

Yes put them on separate objects

hollow zenith
#

Btw any tips on speeding up Unity 6, even with this minimal project it takes ~5 seconds for the game to enter play mode.
I am using SSD, this is a best time to mess with things that would otherwise break my project ๐Ÿ˜„

ripe shard
wintry quarry
austere crypt
#

how to fetch all type of user defined object under UnityEngine.Object?or only UnityEngine.Object?

wintry quarry
#

You could find all derivatives of MonoBehaviour and ScriptableObject but that will include a lot more than "user defined" types

austere crypt
#

just want the type

wintry quarry
#

For what purpose

austere crypt
#

creating searchprovider

#

private static IEnumerable<SearchItem> FetchItems(SearchContext context, SearchProvider provider)
{
if (context.empty)
yield break;

    var types = Assembly.GetExecutingAssembly().GetTypes();
    Debug.Log("-------------------" + types.Length);
    Debug.Log($"Total types found: {types.Length}");

    foreach (var type in types.Where(t =>
        t.Name.IndexOf(context.searchQuery, StringComparison.OrdinalIgnoreCase) >= 0 &&
        typeof(ScriptableObject).IsAssignableFrom(t)))
    {
        Debug.Log($"Yielding type: {type.FullName}");
        yield return provider.CreateItem(context, type.FullName, null, null, null, null);
    }
}
wintry quarry
#

You could just check AssemblyCSharp for such types

#

but that will of course not include assembly definitions

austere crypt
#

didnt know about that assembly stuff

grand snow
#

you already pinged me elsewhere what are you doing

austere crypt
#

finding help from someone else

#

3 head better than 2

hollow zenith
#

After disabling entering play mode is instant ๐Ÿ˜„

#

Damn so many years and I was doing it wrong apparently.
So:
Reload scene is needed for profiling to get more accurate data
Reload domain is to make sure the game state is properly reset(probably good later in development, but most likely useless in protyping)

grand snow
#

At some point you will get problems if domain isn't reloaded. ive had junior devs not fully understand issues they had cus of it and its a pain to debug with em

hollow zenith
#

I wonder if Hot Reload is taking advantage of that(I had issues with it not resetting game state I think)

#

perhaps there is a shortcut to reload domain on demand? so I dont have to reload it every time, but only once in a while

hollow zenith
#

Thanks
basically disabling reload domain is keeping the state of all variables from what I am reading

grand snow
#

Yea everything is kept, you probably want scene reloading at a minimum so those instances are new.

hollow zenith
#

So, how do experienced devs work with Unity?
Do you enable scene reload only, or do you disable both and manually refresh or reenable it every once in a while?
Or do you accept 5-10 seconds wait time each time you enter play mode?

wintry quarry
#

They do lots of different things.

#

I would say 5-10 seconds is pretty reasonable to wait

hollow zenith
#

I agree as the project grows, but right now I have 2 colliders, so it's less acceptable I think, unless I enter playmode too often maybe ๐Ÿ˜„

#

well disabling the above made it almost instant so that helps testing collisions and what not

grand snow
#

i have full reloading on and a typical play takes like 3-8 seconds but i have a good pc

hollow zenith
#

What exactly do I need in my PC to get similar results? Better CPU or GPU?

#

I have SSD/32gb ram(tho half is being used by system and other apps)

#

My PC is few years old so it might be time to get a new one

grand snow
#

to me its not worth the time to make no domain reload working and it could cause bugs that dont exist in real builds.
better cpu, decent ssd and good ram

hollow zenith
#

Can you DM me your build and how much it costs? I am curious if its affordable for me currently.

#

It's been 6+ years for my current PC, so it might be time to get a fresh one.

#

on my larger projects it would take 20+ seconds sometimes ;_;

#

Even with disabled reload of domain/scene the variable in my object did reset properly, it might be something else then

#
    [SerializeField] TextMeshProUGUI textField;
    [SerializeField] int numberGoUp;

    void Update()
    {
        numberGoUp++;
        textField.text = numberGoUp.ToString();
    }
late burrow
#

what was the expected way of turning class into readable string of variables

wintry quarry
#

You mean... serialization?

late burrow
#

yes

#

clearly not json it doesnt support anything

wintry quarry
#

I don't understand what you mean

late burrow
#

i want turn my class into text file so somebody can fill this out and i re load it back into the game

wintry quarry
#

You can use any serialization format you want

#

including json

#

yaml

#

a custom format

late burrow
#

no it doesnt even have arrays

wintry quarry
#

json has arrays

late burrow
#

not mentioning dictionaries or nested classes

wintry quarry
#

huh

#

You seem confused

#

maybe you're confusing Unity's JsonUtility with the json format

hollow zenith
#

one of the json parsers doesnt support dictionaries, but there is another one that definitely supports them.

slender nymph
late burrow
#

well whenever i read about solutions it has overcomplicated loops in order to do so

#

i dont want custom setup for specific class but one function solution

wintry quarry
#

No idea what you're talking about with loops

#

the serializer does everything

#

as long as you conform to its rules

late burrow
#

ok

#

so newtonsoft.json works?

wintry quarry
#

yes it works

late burrow
#

its build in

wintry quarry
#

it's a package

late burrow
#

from what i remember

#

oh right i might had it from other stuff installed

late burrow
#

well how will it serialize infinite class loop then

late burrow
#

yeah newtonsoft one seem as effective as default one

#

it doesnt want touch my custom class list

slender nymph
#

show what you tried

late burrow
#

ok it doesnt work on statics?

wintry quarry
#

You cannot serialize static variables, no

#

they serialize objects

slender nymph
#

technically it can

#

it's just opt-in like for private members. the JsonProperty attribute should be enough for it

swift crag
#

serializing a static member sounds very weird

wintry quarry
#

yeah it doesn't make much sense

slender nymph
#

yeah it is very weird, but it is possible ๐Ÿคทโ€โ™‚๏ธ

wintry quarry
#

likely the design of the data model is off in the first place

swift crag
#

it's like trying to

#

uh, i need to think of a metaphor

#

it's like trying to mail somebody the intangible concept of a bicycle

late burrow
#

ah it actually notices these
Self referencing loop detected for property 'helditems' with type 'System.Collections.Generic.List`1[global+usableitem]'. Path 'helditems[0]'.

#

so i guess i have just to think of way to store variables in one place

#

like root class

wintry quarry
#

Yes... just make a container object

#

public class GameData { ... all the stuff ... }

late burrow
#

also isnt class gonna fall apart when recreating it?

#

it only holds its values how its gonna know custom class inside another custom class

#

or it creates using only values provided and rest are nulls

wintry quarry
#

Not sure I follow what you mean

#

how its gonna know custom class inside another custom class
This is not a problem

#

it's not even a problem with JsonUtility

hollow zenith
#
[Serializable]
public class SaveGameData
{
    public float Version = 0.1f;
    public GameSettings Settings = new();
    public GameData GameData = new();
    public List<PartyData> PartyData = new();
    public List<AreaData> AreaData = new();
    public InventoryData InventoryData = new();
}

Following some help of people here I wrote this in the past for serializing game data(for saving purposes)
Each of these types such as PartyData/AreaData is another class.

Saving/Loading:

//save
string filePath = Path.Combine(Application.persistentDataPath, _SAVEFILENAME);
string saveData = Newtonsoft.Json.JsonConvert.SerializeObject(SaveGameData);

// load
string saveData = File.ReadAllText(filePath);
SaveGameData save = Newtonsoft.Json.JsonConvert.DeserializeObject<SaveGameData>(saveData);

It worked fine with no issues.

#

That means it works with lists, nested classes, nested lists of classes with lists etc

late burrow
#

though i need go through everything slap jsonproperty on everything first

hollow zenith
#

Your game logic can directly write to those classes as well(that's how I did it)

late burrow
#

to not miss data

hollow zenith
#

I don't know what do you mean, but if you separate the data you want to serialize into it's own object then it's no issue

#

Because you just serialize whole object

#

[Serializable]
public class SaveManager
{
    public static SaveManager Instance;
    public SaveManager()
    {
        Instance = this;
    }

    public SaveGameData SaveGameData = new();
}

I did this to have access to all save data globally, so all my runtime scripts could directly create/delete/add w/e they needed.
For example my Inventory script would be able to access SaveManager.Instance.InventoryData and read/write to it.

#

I am sure there are better ways, but this was simple to use, but I had to rewrite some of my code which was worth it by the end.

#

if I don't find a better way, I will be using this approach in the future.
It makes saving/loading easy.(which includes serializing json so you can read those files from the player, which I assume might be related to modding?)

true owl
#
   void Move()
    {
        if (!isDashing)
        {

            /* if player is on ground or rail, have holding diagonally affect the same as just horizontally 
                otherwise just use the x input that comes in normally */
            float adjustedMoveInput = isGrounded || isOnRail ? (moveInput.x == 0 ? 0 : (moveInput.x > 0 ? 1 : -1)) : moveInput.x;
            float targetSpeed = adjustedMoveInput * maxPlayerSpeed;
            
            // normal movement
            rb.linearVelocity = new Vector2(Mathf.LerpUnclamped(rb.linearVelocityX, targetSpeed, Time.deltaTime * acceleration), rb.linearVelocityY);
            Debug.Log("adjusted move input: " + adjustedMoveInput + " target speed: " + targetSpeed + " time + acceleration: " + Time.fixedDeltaTime * acceleration);

            Debug.Log("Linear velocity: " + rb.linearVelocity);
            /* if they let go of the button of either of the control buttons,
                and are at the maximum player speed, apply some drag */
            if (Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.D))
            {
                rb.linearVelocityX = Mathf.LerpUnclamped(rb.linearVelocityX, 0, Time.fixedDeltaTime * dragFactor);
            }

        }

        animator.SetBool("isRunning", true);
    }

can someone explain whats wrong with this code for the movement, it seems like the acceleration doesn't really work and that when moving left the top speed reached is walways less than the right side

hollow zenith
north kiln
#

Presumably just hasn't been updated. As the contents of the method is completely irrelevant to what's being stated by the accompanied text, it matters so little

hollow zenith
#

Makes sense, I was a bit confused that they don't follow their own guidelines so I assumed there must be some reason.

#

I am reading up on sealed classes.
Usually I am told to set all my properties as private by default and make them internal/public only when needed.
Should I do the same for sealed classes? After all it seems to prevent inheritance which I most often don't need so I might as well make it sealed and remove this modifier if I ever decide to inherit from that class?

timber tide
#

who has time for that

west radish
cosmic dagger
west radish
#

Especially if you know you'll definitely be accessing the class later on without a doubt

cosmic dagger
#

nope . . .

west radish
#

Oh wait ignore that lol

cosmic dagger
#

properties and fields (variables) are members of a class . . .

west radish
#

it's too late to be thinking ๐Ÿ˜†

hollow zenith
#

Yeah I meant fields and properties of a class.

#

So now I got to a next thing:

In general, use the following format for code samples:
- Use four spaces for indentation. Don't use tabs.

Should I assume that VS uses spaces when I press tab and I don't have to worry? ๐Ÿ˜„

#

Luckily I had VS open and tested it, that seems to be the case, so I am saved!
I suppose that VS automatically follows the microsoft guidelines so a lot of these things are done for me.

timber tide
#

it probably does cause copy pasting my code over to godot creates a lot of white space

#

odd choice not to include tabs

#

I guess it makes sense that compiler doesn't complain if everything is misaligned because of a rogue space

hollow zenith
#

So spaces are actually better, someone sent me an example in the past with a tab character.
It can vary in size in a text document based on some things I am not familiar with ๐Ÿ˜„

#

I was surprised when I saw this, but something like word might display tab at various sizes depending on where it appears in the text and it's apparently a normal thing.
It might be related.

#

There are actually many reasons for it now that I am reading up on that

west radish
#

I use 2 spaces, I find tabs can become a pain especially when you start moving code around or you copy+paste stuff

#

You can configure VS to use spaces when you press the tab button

late burrow
#

whats the reverse to [JsonProperty] to not include publics

wintry quarry
#

Also JsonProperty is not needed by default

#

only if you use MemberSerialization.OptIn

#

If you use OptIn, then Ignore is not needed

sand schooner
#

my player has a raycast to check if grounded (its the cyan line in the screen shot) and you can see it is definitely hitting the ground, yet it is not detecting a hit. Any ideas?

wintry quarry
#

Lots of things could be wrong

#

you'd have to share details

sand schooner
#

this is the box colider of the surface the player is on:

wintry quarry
#

And then show the code for the raycast

#

and the layermask you're using, etc.

sand schooner
#

there is no layers as far as I know (I just set it to everything for test)

sand schooner
#

and check ground code:

wintry quarry
#

clearly it's hitting

sand schooner
#

good point lol

#

right after it draws the ray cast, that is the only place in the code it sets isGrounded to true

wintry quarry
#

What makes you think it's not working? Presumably you have an issue elsewhere in the code.

sand schooner
#

I can spam jump and fly up

#

aka I can jump when I am in the air

wintry quarry
#

You'd have to show the rest of your code

wintry quarry
#

not that it never thinks there is one

#

You should log which object you're hitting

#

e.g. Debug.Log($"The raycast hit {hit.collider}!");

sand schooner
#

"The raycast hit FirstPersonController"

wintry quarry
#

there ya go

#

seems obvious what's happening now ๐Ÿ˜›

sand schooner
#

Its hitting the player?

wintry quarry
#

this is why you need a layermask

sand schooner
#

Ah okay I will look into layer masks

#

thank you!

hot laurel
sand schooner
#

it is a problem that the platform the player is on is the parent of the player?

#

oh nvm I can assign it to just the parent ๐Ÿ™‚

last edge
#

say what do you guys use to push unity onto github? because github desktop isnt detecting my changes for some reason

wintry quarry
#

but it sounds like you're probably just doing something wrong

plucky copper
#

I want to suck all RigidBody2Ds into the center of the screen.

How would I go about doing this?

#

Ideally the force would be centered around some placeable GameObject.

wintry quarry
plucky copper
#

Thanks!

near wadi
#

Can you simply put a Button in a Script that shows in the Inspector,, when you put it on a Prefab, or do i have to use an Editor Script everytime?

late burrow
#

where i put jsonobject prefix so it stop erroring when trying deserialize

opal zealot
#

Also sry

near wadi
#

no worries ๐Ÿ™‚

late burrow
#

json really doesnt like dictionaries i remembered that

wintry quarry
#

json doesn't care about dictionaries

#

you are again thinking of JsonUtility in Unity

#

json itself basically is a dictionary

late burrow
#
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.```
near wadi
wintry quarry
late burrow
#

by dont match you mean missing fields? because obviously i havent took ones i dont need

wintry quarry
#

in the way it says in the error

near wadi
tranquil mango
wintry quarry
late burrow
#

well i basically have json of same object printed right before it

#

i just try to load it back and it errors out

wintry quarry
#

you'd have to show the json you are trying to deserialize and what type you're trying to deserialize it into

#

Hard to help without seeing the code/context and the data

late burrow
#

errors on this
public Dictionary<string, bodypart> parts = new Dictionary<string, bodypart>();

wintry quarry
#

Doesn't seem like it, based on the error

#

seems like you have a bodypart array somewhere

#

again, hard to help without seeing the code and the data

late burrow
#

only in the constructor, i dont use arrays anywhere else

wintry quarry
#

hard to help without seeing the code and the data

late burrow
#
    public class character
    {
        public string name = "randomchar";
        public int health = 1000;
        public int oxygen = 300;
        public int stamina = 100;
        public int inteligence = 40;
        public Dictionary<string, bodypart> parts = new Dictionary<string, bodypart>();
        public List<usableitem> helditems = new List<usableitem>();
        public character(bodypart[] parts, int[] stats = null)
        {
            foreach (var part in parts)
            {
                this.parts.Add(part.name, part);
            }
            if (stats != null && stats.Length == 4)
            {
                health = stats[0];
                oxygen = stats[1];
                stamina = stats[2];
                inteligence = stats[3];
            }
        }
    }```
wintry quarry
#

It's because your constructor expects an array of bodyparts:

public character(bodypart[] parts, int[] stats = null)```
#

you need to provide a parameterless constructor for the serializer to use.

late burrow
#

for every class?

wintry quarry
#

Since you defined a constructor for this class with parameters, it doesn't have a parameterless contstructor. The deserializer is forced to try to kludge things into this one

#

if you don't provide any constructor there will be an empty one by default

late burrow
#

but what about other classes that use parameter

wintry quarry
#

what about them?

#

you can define more than one constructor

late burrow
#

i use constructors to pass data more compactly

wintry quarry
#

Not a problem

wintry quarry
late burrow
#

ok from what i see i need change every class constructor

wintry quarry
#

I don't know where you're getting that from

#

Add a parameterless constructor to any class that needs it

#

you don't need to change any of the existing ones

late burrow
#

i mean i dont have problem with removing them

#

just more data in bulk at once

wintry quarry
#

I never suggested removing them

late burrow
#

JsonSerializationException: Unable to find a constructor to use for type global+usableitem. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'parts.arms.functions.hit.name', line 1, position 174.

wintry quarry
#

use it

#

as the error mentions

late burrow
#

but im not giving it data required to use it

#

i expected json can skip constructor

wintry quarry
#

there is no data required to use it

#

because it should be a parameterless constructor

#
[JsonConstructor]
public MyClass() {}```
late burrow
#

ah this

umbral bough
wintry quarry
#

Given the links to the newtonsoft docs...

umbral bough
#

sorry, I'm blind ๐Ÿคฆโ€โ™‚๏ธ

#

I've been working on camera controls for a character.
I got it right for the most part, however, if the character(a ball) spins upside down(I think), the input is inverted.
Here's the code:

private void Tilt()
{
    var ea = transform.eulerAngles;
    var amount = Input.GetAxisRaw("Mouse X") * _tiltSpeed;

    // These 2 lines help with the inversion a bit
    amount *= ea.x >= 180 ? -1 : 1;
    amount *= ea.x <= -180 ? -1 : 1;

    // Combine the rotations
    transform.Rotate(Vector3.up, amount, Space.World);
    transform.eulerAngles = new(ea.x, transform.eulerAngles.y, ea.z);
}

The 2 lines of code I mentioned help a bit but not fully.
Is there a more proper way to handle this?
Thanks in advance and please @ me!

buoyant finch
burnt vapor
# buoyant finch

You made a mistake in your !code formatting, please use a paste site when you're sharing this much code ๐Ÿ‘‡

eternal falconBOT
sand schooner
#

any ideas why a couple of my buttons work in the editor, but not when I build and run the build? They detect the mouse over, but the click nothing happens

buoyant finch
#

https://paste.ofcode.org/38DpdAUqHsswuQ9ja893JQ5
so basically I have made a function to freeze the animation states but I don't want that functionality for the run animation.I made something like it but the run animation loops pls help me fix it

verbal dome
buoyant finch
verbal dome
#

You did it wrong

burnt vapor
#

Also make sure your build does not rely on editor namespace features. Those are stripped out in builds

sand schooner
#

Where can I see build errors?

near wadi
#

Well, it only took about 10 times longer than it would have for me to figure it out myself, (about 1000 times the time it would take one of you programmers), but i successfully got CGPT to write me another Script-Editor tool! :/ ๐Ÿ˜ we laughed. we cried. i accused it of being satan a couple times. in the end, i have a functioning tool though ๐Ÿ™ƒ

burnt vapor
sand schooner
#

found the issue, thanks!

#

on another note, the cursor is locked and hidden when running the game in the editor, but not in the build

burnt vapor
#

Generally implementing cursor specific behaviour is best done by testing it in actual builds since that's how it ends up as

sand schooner
#

I use this Cursor.lockState = CursorLockMode.Locked; but I guess it does not work in builds?

#

nvm all good now ๐Ÿ™‚

nimble cliff
#

Hello,

I have some data point in Redis which I would like to process in unity (Redis data -> NativeParallelHashMap) . I tried to download and add NRedisStack by copying the dll in a Assets/Plugins folder but it does not seems to work ( netstandard 2.0 vs netstandard 2.1 I guess ).

I tried to lookup but I could not find a way to add a redis client to unity.

Thanks

verbal dome
verbal dome
#

How does it act if you remove that part?

umbral bough
umbral bough
#

I was doing that thing in the first place because I want my other axes to be left untouched

umbral bough
verbal dome
#

Oh also get rid of the amount *= lines for now. I need to know what is the base behaviour here

#

Why is the rigidbody's Y rotation frozen

#

In the constraints tab

#

(Shouldn't use transform to move/rotate a rigidbody anyway)

umbral bough
umbral bough
verbal dome
#

What object is this script attached to

umbral bough
#

object that's got the rigidbody and a collider, and is also a parent of the model

verbal dome
#

Of course transform will affect the rigidbody then

umbral bough
#

I see, well what are my options then?
It's supposed to be a half rigidbody, half mouse based movement and this just seemed like the most intuitive solution.

#

once the object goes past a certain point(180deg X I assume), the rotation just flips

verbal dome
#

Video is private

umbral bough
#

my bad

#

it should be available now

verbal dome
umbral bough
#

Issue is, I am not rotating the camera here, I want to rotate the blade(which uses rb) :/

verbal dome
#

Why is that an issue

#

Use rigidbody methods/properties to move and rotate it

umbral bough
#

I see, but if you add force to the rigidboy, it's not like an instant move.
Say I was to add some torque to the right, it would keep going for a bit(unless I increase angular damping which would mess w X rotation).
Is there a method for just rotating it that I am unaware of?

verbal dome
#

You can't make the blade rotate perfectly/instantly and have it respond correctly to collisions if you rely on the physics simulation

#

Instant move != physics

#

You could achieve something like it if you do your own collision checks though

#

With boxcasts and whatnot

#

But you'd have to do it in substeps if you are rotating (since a cast can't rotate)

umbral bough
#

I see, this is quite weird tbh.
I'll try the rb approach and see if that feels bad.

buoyant finch
#

in this code the running anim works well it switches to the walk animation but the player is unable to move like it glitches out after 1 or 2 key presses and I want it to switch to the 2nd frame of the walk animation in the blend tree
https://paste.ofcode.org/b7sUm2sgjL77HmjY3Udq2z

visual linden
# buoyant finch in this code the running anim works well it switches to the walk animation but t...

Hey :) How come you're using a coroutine for moving the player when you're already calling the function through Update?
I would also guess that you don't want to read any further input whilst isMoving is true, but that whole logic doesn't make a ton of sense to me at a glance.
( Would also recommend posting this in #๐Ÿƒโ”ƒanimation instead where animation/animator related questions usually go )

north scroll
#

so im starting to learn about splines, trying to make a race track obstacle type game. I have the player object moving along the spline correctly atm, but the input keys i have set up to move it left and right don't move the player at all. It looks like the player transform is always set to the spline's points. Which makes sense, and when trying to find more info it looks like a neat "trick" is to have a parent object on the player be the splines target which can allow the player child to move "independently" but that's still not working either. Any advice or explaination on a spline setting or feature im missing ?

faint osprey
#

is it better to use broadcast message or actions for bullets hitting things

hexed terrace
#

actions

faint osprey
#

how do i set that up cause my enemy needs a refrence to the bullet script no?

#

and they get instantiated

hexed terrace
#

It may do, it may not do.. depends on what's required for the game.

You either pass required references to the instantiated object on spawn, or it gets them when it needs them (eg: on collision -> TryGetComponent<T>())

faint osprey
#

oh i see

#

wait no i dont

faint osprey
hexed terrace
#

you're talking far too generally

#

your bullet will probably have an OnCollisionEnter() or OnTriggerEnter() method, which will be called when the bullet hits something.. you do the functionality of the bullet hit in this method, which could include getting the required components it needs to interact with - eg: health

faint osprey
#

yeah thats what im doing but then when i invoke the action the enemy script hasn't bound the action because it couldnt get a reference onEnable

hexed terrace
#

then you need to change your logic, if it can't do it in OnEnable it has to do it elsewhere... like... in OnCollisionEnter

#

The enemy doesn't need to know about the bullet

faint osprey
buoyant finch
hexed terrace
faint osprey
hexed terrace
#

Tbh, your 'enemy' class shouldn't be dealing with damage anyway. You should have a 'Health' class, so you can put this on anything that requires damage.. and then you get the health component

never use broadcast message - it uses strings, which is slow and extremely error prone with no easily traceable logs

final kestrel
#

It is always good to convert world positions-rotations into local positions-rotations or vice versa,when doing for example, slerping right?

#

Explicitly I mean

astral falcon
final kestrel
astral falcon
final kestrel
#

My camera is a child object though.

astral falcon
#

and your parent is moving and rotating?

final kestrel
#

Yes

#

I move my playerObject and Camera object seperately.

#

While slerping the rotations

astral falcon
#

then you will , no matter if local or world, have a hard time rotating parent and child at the same time

#

is it third person with orbiting camera?

final kestrel
#

No its a first person controller.

#

I rotate my player object on world position while doing my camera on local

astral falcon
#

so you could just move your player to look the direction and your camera just be a stationary child?

final kestrel
#

Not stationary. I dont to anything with yaw on my playerCamera. Thats my playerObject's work to do. While it rotates the yaw I just change my camera's X axis so it faces up and down

astral falcon
#

So again, you do not need your camera to rotate, if you are in a first person scenario, right? You could still rotate your parent player on Y to look at the direction you want with your camera.

final kestrel
#

Yeah but what if the lookTarget is above the player though? I would not want to mess with my playerObject's X axis

#

Rotating the player on Y brings my playerCamera with it while I'm also manipulating my camera's X to match wherever the lookTarget is

#

This solution may not be the best but thats what I come up with ๐Ÿ˜„

#

When I rotate them both it works

swift crag
#

For example, I have an IK system that clerps (amazing word: cylinder lerp) a target to a point

#

It operates in the local space of the character

#

This way, if they rapidly spin in place, their hands will naturally with move with them

#

instead of being left far behind

final kestrel
#

I see. On your point, you're using its world position right?

astral falcon
swift crag
#

No, I'm using the character's local-space positions

#

I transform them back into world-space to use the positions, of course

#

But I reason about them in local space

final kestrel
#

Ah okay so transforming is necessary

final kestrel
#

I understand why I would want to use localSpace transforms but when it comes to world space and why they might not behave as expected when slerping in my case. It gets a bit confusing because I cannot actually picture it in my head

astral falcon
#

because converting it to local space will take into account th eparent rotation. If you dont do that, it will just try to force its own rotation no matter what. Thats when things start to jitter or offset

final kestrel
#

Hm makes sense. Could unity be handling those in some cases?

#

Converting local and world rotations operations I meant

swift crag
#

I don't know what that would entail

astral falcon
final kestrel
#

Hm okay. I'll read more stuff on it it seems. It is really hard to rotate objects for me with all the methods I can use. I'm just trying to find a way to make it right ๐Ÿ˜„ Thank you both for your time.

astral falcon
final kestrel
#

Yeah I will definitely keep doing that. Thanks!

late burrow
#

if i have 2 static constructors which one runs first

verbal dome
swift crag
#

on two different types, presumably

#

It's called automatically before the first instance is created or any static members are referenced. A static constructor is called at most once.

wintry quarry
#

So it's basically random

swift crag
#

what docs are you looking at?

wintry quarry
grand snow
#

If these are serialized types its a gamble. If you are who makes and uses it i guess you do have control but its not reliable

swift crag
#

we're looking at the same page

north scroll
#

how does the spline animate component work with the movement of the gameobject its under? I've got a basic scene set up that works having a GO move around the rounded square path but im trying to include left/right input (similar to an endless runner), but it looks like the spline animate is constantly adjusting the position of the GO to align with the spline which makes sense.

I found a forum that gave the solution of using the track's points and manually updating the position instead of using the spline animate by using the spline points to have the GO's forward direction be the next spline and just having it constantly move forward instead. I might just end up using that solution but I figured i'd ask if there was an easier way cuz I can't seem to find it

languid spire
wintry quarry
#

I see, that's a weird statement they make then

swift crag
#

It does indeed say "The user has no control on when the static constructor is executed in the program." later on

#

I wonder who "The user" is here

faint osprey
#

is there away to increase the time before a rigidbody falls asleep after not being used

wintry quarry
#

Presumably the C# programmer

wintry quarry
#

Check the docs

#

Well it's not based on time actually

#

It's based on "energy"

faint osprey
#

where is this sorry i cant find it

wintry quarry
#

Which... I'm now curious how that works. Is the engine checking if there's a collision going on? How does it differentiate between resting on a table and being at the peak of a parabolic arc?

swift crag
wintry quarry
#

You can Also just set it to never sleep

swift crag
#

my bird kept falling asleep mid-air

#

๐Ÿ’ฅ

wintry quarry
#

Lol

faint osprey
verbal dome
languid spire
swift crag
wintry quarry
faint osprey
#

oh no just for the player

swift crag
#

go nuts

wintry quarry
#

Then no

#

It's fine

swift crag
#

The performance impact of something is the product of two factors:

  • How expensive is it?
  • How much am I doing it?
#

As long as one of these two numbers is small, you're probably fine

#

If you have one player, the player can do complex things. If your enemies do simple things, then you can have many enemies.

languid spire
#

I remember a few months ago we had a problem with a rigidbody not working, turns out it was asleep and did very weird things

verbal dome
#

At least in PhysX it has a timer

swift crag
#

note that you can explicit tell a rigidbody to wake up

#

it doesn't look like you can check if it is asleep, though

languid spire
swift crag
#

oh, there it is

#

IsSleeping()

languid spire
#

lazy bloody rigidbodies, I bet they are all Gen Z or millennials

swift crag
#

Unreal was giving me a real headache there

#

It was completely unresponsive to the "sleep threshold" settings

#

which you'd think would be relevant to affecting the sleep threshold

#

i think i wound up just applying a very small force to my bird every frame

warm rock
#

!Code

eternal falconBOT
warm rock
#

help me with this, i was following the CodeMonkey 2024 Unity Beginner/Intermediate Tutorial and its stuck on this point, the raycast is working non-stop (thats what i think since i made it stop moving when Raycast is hit)
https://paste.mod.gg/wttwimstgggf/0
the object is on the ground so raycast should meet it, i tried changing location of object but raycast sees it even if its above it

echo ruin
#

Not sure if the code is viewing correctly on my phone, but it looks like you put all of the code in Update()

#

Which is a bit excessive.

#

Only update the things you need to change between frames

warm rock
#

i followed the CodeMonkey tutorial... tbh im bad at coding im trying to learn
but i will try removing some stuff

stiff birch
warm rock
stiff birch
#

OK. And the issue is the raycast always hit something ?

wintry quarry
stiff birch
warm rock
stiff birch
warm rock
# stiff birch Can you share the video you're following pls ?

๐Ÿ’ฌ This was a ton of work to make so I really hope it helps you in your game dev journey! Hit the Like button!
๐ŸŒ Course Website with Downloadable Assets, FAQ, Related Videos https://cmonkey.co/freecourse
โค Follow-up FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
๐ŸŽฎ Play the game on Steam! https://cmonkey.co/kitchencha...

โ–ถ Play video
#

2:11h of the video

#

at 2:11:14 exactly

stiff birch
#

You changed the value of player radius because you changed your actual player ? Like you didn't use the exact setting they use in the video ?

warm rock
#

i cant remember why, i tried reverting it to .7 again... didnt work

stiff birch
#

Is your character the same as in their video, an empty gameObject called player with a model as child ? did you remove the capsule used previously in the tutorial ?

warm rock
#

i didnt use a capsule

stiff birch
#

Earlier in the video, they use a capsule as visual, which holds a collider, so i wanted to make sure it's not on your side

warm rock
#

i dont have it

earnest wind
#

is it impossible to have a Vector2 is unity editor for buttons?

hexed terrace
#

the button component can't have Vector2, no

earnest wind
hexed terrace
#

Only bool, string... and.. something else int maybe

earnest wind
#

make a string and break it down with regex?

wintry quarry
hexed terrace
#

I don't know the best solution in your case. I don't use these

#

There you go, Prae has given you the way

earnest wind
warm rock
stiff birch
# warm rock i dont have it

At 1st glance, appart from the value difference (which should not have any impact), i don't see any difference between their code and yours

wintry quarry
stiff birch
#

Probably. Sorry I can't help much, but I don't have any more explanation for the moment

warm rock
wintry quarry
#

first thing you need to do is check which object your cast is hitting

warm rock
wintry quarry
# warm rock wdym?

debugging is the process of analyzing and investigating your code and how it runs to fix bugs

wintry quarry
#

Use Debug.Log and print it.

warm rock
#

ohhh

#

Debug.Log(What?)

#

what object should i write for asking the game what Raycast is hitting

rich adder
warm rock
#

ok ty

wintry quarry
#

right now you don't have one at all

warm rock
#

then what do i write there to debug it??

warm rock
#

dont understand whats after the first if statement...

wintry quarry
#

it's doing a raycast

#

but uhh

warm rock
#

should i just copy that there?

wintry quarry
#

the innermost if statement in there is not necessary

wintry quarry
#

you're doing capsulecast I thought

warm rock
#

ye

wintry quarry
#

Look at the docs

#

Look for the version with the out Raycast parameter

#

use that one

warm rock
#

i read it all, didnt understand most of it. idk what to do now, im more confused

wintry quarry
#

what part is confusing you

warm rock
#

all of it

wintry quarry
#

that's not helpful

warm rock
#

sry ;-; i just want to know what is hitting it . . .

wintry quarry
#

I'm explaining how to do that to you

#

There's even a code example on the page

#

that has the RaycastHit param

warm rock
#

i tried reading all of it, i didnt understand it... i will reboot system and come back

rich adder
stiff birch
#

You currently have this : !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * playerHeight, playerRadius, moveDir, moveDistance);
So you have point1, point2, radius, direction and maxDistance. So now you need to insert an out parameter to follow the prototype of public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

proper cobalt
#

hello i am new to unity and coding and I think i understand the class system (The only language i know by memory is JS so im not great with class coding yet) and I just wanted to check my understanding in that classes are a system to basicly say what group things are in like if you had a class "Weapons" then you could put the code in for all of the weapons?

stiff birch
#

you can ignore the last 2 parameters as they are optionals (they have an = sign)

proper cobalt
#

poo

wintry quarry
#

You can think of a class as a "blueprint" for a type of object

proper cobalt
#

oh ok

wintry quarry
#

The code in the class describes how an individual object of that type behaves and what data it stores etc.

#

and what things you can do with it

proper cobalt
#

ohhh i see that makes sense

wintry quarry
#

From that, you can create any number of instances of the class, which would be objects that behave as your class describes

proper cobalt
#

oh i see thank you so much

warm rock
rich adder
#

they are given the defalt values

warm rock
rich adder
#

OR you can use myparam: thevalue and you can order them how you please

warm field
#

how would i do an if something and something? the code doesnt seem to know what "and" is

rich adder
#

c# doesn't write AND

#

also easily googleable.

warm field
#

oh, thanks

warm rock
rich adder
warm rock
#

oh i meant that ye

formal hill
#

(Sorry for the code being in a text file discord wouldn't let me send it other wise)

Can someone explain to me why the creditsPanel will open fine if I don't have any other if statement to close it, but the second I add an if statement so that when you're in the credits scene, it will close it by pressing the return button it won't even open?

eternal falconBOT
formal hill
warm rock
#

like this?

warm field
#

also how do i make an else

warm rock
#

i just added out RaycastHitOutput hitinfo in the last part

stiff birch
warm field
#

also for some reason && is invalid expression tern

formal hill
#

Can someone explain to me why the creditsPanel will open fine if I don't have any other if statement to close it, but the second I add an if statement so that when you're in the credits scene, it will close it by pressing the return button it won't even open?

https://paste.mod.gg/upmbddfkidfo/0

warm field
#

oh, && cannot be applied to operands of type cursorlockmode and bool?

rich adder
#

you have to access whats inside

#

also dont crop

rich adder
#

cursorlockmode is an enum
it can only be used in if statement if you are comparing

warm rock
warm field
#

        if (Input.GetKeyDown(KeyCode.Escape)) && Cursor.lockState = CursorLockMode.Locked; // Unlock cursor if player presses Esc
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;

            else Cursor.lockState = CursorLockMode.Locked && Cursor.visible = false;
        }
warm rock
rich adder
tough tartan
#

https://youtu.be/Kgjth3nRsFc?si=fkq31j7IlYmgKQ4C 17 minutes for some reason im unable to turn when moving mouse

Learn how to create your own classic First Person Shooter in Unity!

Get the assets for this series here: https://www.dropbox.com/s/juihs7yq93x1aon/GPJ_FPS_Assets.zip?dl=0

Don't forget to hit that like button and if you'd like to see more gaming goodness then subscribe for more!

Support the show by pledging at http://www.patreon.com/gamesplu...

โ–ถ Play video
warm field
rich adder
warm rock
#

cant see Collision or collision

rich adder
warm rock
warm field
#

basically what you see in most games(so you can access settings n such when you pause)

warm field
warm rock
rich adder
# warm field yea

why not just a bool
isPaused = !isPaused
Cursor.LockState = isPaused ? cursor.lockstate = unlocked : locked

warm field
#

so i create a bool

rich adder
# warm rock

show how you created the hitInfo. That aint right

rich adder
#

don't you see its erroring

rich adder
warm rock
rich adder
#

no?

warm rock
#

ok sry, i will try reading signature thing again

rich adder
#

is that was written on the docs?

warm rock
rich adder
warm rock
#

i will try reading it again . . .

warm field
#
 if (Cursor.lockState = isPaused)

this gave an error

rich adder
#

because its nonsense

#

you're assigning a bool to a enum

#

not even remotely close to the example i wrote

warm field
#

i made a public bool isPaused

rich adder
#

and?

wintry quarry
#

= is for assignment

rich adder
#

hows that have to do with what I said @warm field

#

if you're confused on the ? just ask

rich adder
hot laurel
#

just a hint - its about assigning an enum value based on bool state by ternary operator, not about assigning bool to an enum

rich adder
#

maybe a should've just used an IF else statement as example

warm field
warm rock
rich adder
rich adder
warm field
#

? is question, and : is choice?

rich adder
verbal dome
#

I mean what is the cursor.lockstate = unlocked part

rich adder
rich adder
warm field
#

so if does Cursor.lockState = isPaused? Cursor.lockState = unlocked : Locked

formal hill
#

Can someone explain to me why the creditsPanel will open fine if I don't have any other if statement to close it, but the second I add an if statement so that when you're in the credits scene, it will close it by pressing the return button it won't even open?

https://paste.mod.gg/upmbddfkidfo/0

swift crag
rich adder
#

didn't feel like typing the enum 3 times

swift crag
#

It evaluates to either trueResult or falseResult

warm rock
#

i still dont understand

wintry quarry
rich adder
warm rock
#

i tried adding the RaycastHit hit

rich adder
#

you literaly have it correct almost, just wrong type

astral falcon
#

If you wanna switch between locked and none, jsut

Cursor.lockState = (CursorLockMode)(trueOrFalse + 1);
#

Expected responses ๐Ÿ˜„

languid spire
wintry quarry
# formal hill Can someone explain to me why the creditsPanel will open fine if I don't have an...

I mean just look at this code.

Read through it line by line. Imagine you're the computer clearly it's going to end up closed, right?

        if (currentState == MenuState.CreditOption && Input.GetKeyDown(KeyCode.Return))
        {
            creditsPanel.SetActive(true);
            startPanel.SetActive(false);
            currentState = MenuState.InCreditsPanel; 
        }

        if (currentState == MenuState.InCreditsPanel && Input.GetKeyDown(KeyCode.Return))
        {
            creditsPanel.SetActive(false);```
warm field
#

i got this:

if (Cursor.lockState = isPaused ? Cursor.lockState = isPaused : Cursor.lockState = !isPaused)
swift crag
#

This is a very perplexing expression

#

It's totally valid, which is what's funny

rich adder
#

you dont need that much nesting

swift crag
#

well, no, it's not

#

isPaused is not a valid value for the CursorLockMode enum

#

since I presume that's a boolean

grand snow
#

I see = not ==

warm field
#

isPaused is a bool

warm rock
tough tartan
#

Lowk need help real quick

wintry quarry
#

doing if (x = y) makes no sense

#

it would be if (x == y)

formal hill
rich adder
#

you see its red?

wintry quarry
warm rock
#

i did, it gave more errors

verbal dome
#

This half arsed example started this whole confusion

swift crag
warm rock
#

i switched RaycastHitOutput with hit

warm field
wintry quarry
swift crag
rich adder
warm field
#

now its this:

if (Cursor.lockState == isPaused ? isPaused : !isPaused)
swift crag
astral falcon
eternal falconBOT
#

:teacher: Unity Learn โ†—

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

swift crag
#

What is the objective here?

rich adder
#

whatever lol OP just needs basic c#

swift crag
#

What are you trying to make your game do?

warm field
languid spire
astral falcon
warm rock
swift crag
rich adder
swift crag
#

The conditional operator picks between two expressions. For example:

bool foo = true;
int bar = foo ? 1 : 2;

foo ? 1 : 2 evaluates to 1, because foo is true, so bar winds up having a value of 1 stored in it.

warm field
warm rock
languid spire
warm field
#

i just realised "junior programmer" pathway exists bruhhh

swift crag
#

You used the wrong identifier for the type of the variable.

rich adder
swift crag
#

The name of the variable does not matter. You can name it literally whatever you want, as long as it's not a reserved word

swift crag
#

Okay, so what is the problem?

warm rock
#

idk

rich adder
#

tell me

hot laurel
warm rock
swift crag
#

That sentence is incoherent.

rich adder
#

we can't se what you did and didn't do unless you show it..

rich adder
#

literally just needed to take oue OutPut idk why you made it so complicated lol

grand snow
#

notlikethis we all used to be like this once but damn

warm rock
rich adder
#

pro tip: don't write extra things that dont exist.

swift crag
#

That is not what you were told to do.

#

You were told to use the correct type name, RaycastHit

warm rock
#

i did type RaycastHit

swift crag
#

You originally wrote RaycastHitOutPut. This is not the name of a type that exists.

astral falcon
#

I wonder what those red lines are below your code parts ... ๐Ÿ˜„

swift crag
#

In what universe is rayhit the same as RaycastHit?

rich adder
willow torrent
#

oh my this is insane

astral falcon
warm rock