#๐ปโcode-beginner
1 messages ยท Page 581 of 1
we cannot make people read screens and think however much we would like to
actually ide packages in unity are installed when you create a new project
the config is done to the ide
nah, they just stich blueprints together and call it programming
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/
Doesnt work in builds ๐
i pushed it onto azure
So nothing shows up in the built game?
im going on 4 years and im still in that mode..
yes
still just fiddling and tinkering
I should've had you add an else block for GUILayout.Label("No hit.");
wait
Do that to be absolutely sure that it's not just a problem with the GUI text being off-screen
no, i just redid logic for Raycasting
@last edge now that you've configured your ide, reread what osmal said ^
It's very handy
It's also a bit spooky -- it runs multiple times per frame
in this case, that doesn't matter
Yeah
whats the class for text displays?
Depends on what component you're using!
isn't it just "Text"? You can check the UI package docs
it works now ty osmal @verbal dome
Still feeling bullied?
@last edge for future reference see Serialization rules
not sure how to find it
google unity ui Text ?
alr
lol kinda but i feel more stupid than bullied
hasn;t changed
ahh.. you'll have that.. happens to the best of us
you make a bit of effort, we will meet you half way
i swapped from gamer maker 2. and lets just say, this is tough not having everything just handed out to me but its fun
i made a bool to check and draw if cursor is in, works in unity, doesnt in build
Have you tried a development build and checked for errors and such
did you do this? I want to be dead-certain that the raycast isn't finding anything
That too. That'll give you an in-game console and provide more information
it finds "Tile" , in build and editor
what did "doesn't work in builds" mean here?
meant that it didnt do what i wanted in build
nevermind
something is blocking
its Tile in build but TileClothWasher in editor
changeTo = PlayerPrefs.GetInt("HighScore");
highScoreDisplay.text = ToString(changeTo);
any ideas why im getting an error to do with tostring taking 1 arguement
I had another collider under the washer
changeTo.ToString();
np.. i think the () at the end is for Formatting
i literally just switched from learning another language where the brackets were for the thing ur changing
lol
It can be like that too in C#, depends on how the code was written
well, it's because you're invoking a method :p
ToString(foo) tries to invoke a method named ToString, passing foo as an argument
ToString can be overridden too, it's handy for debugging
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
ahh. i just know about the 00.00 or F2 etc
Yeah. I use that in conjunction with an OnGUI debug menu
the basic most of the formatting stuff
it's nice to be able to just ToString something and get a reasonable representation of it
instead of just seeing a type name
let me guess, python
you would indeed do str(foo) in python
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 ๐ญ
str is a class, and str(foo) constructs it with foo as an argument
Isn't the problem that your query (whatever it is) is hitting both the grid and the objects?
It doesn't matter if the objects' layer doesn't interact with the grid's layer
I still occasionally call ToString on a list by accident, it just returns the type sadly. I kinda hope it would at least show the Count
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
String.Join() !
I always forget how to use it
partially because Python does it like this
", ".join(blarg)
you can do str.join(delim, iterable)
im using "OnMouseEnter" in a script attached to the toy game object
are you saying it hits both colliders from there?
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
i only use it for debugging so i use a linq .Select() to custom to string elements firstly
Or I could do it consecutively, but not sure if beneficial
String.Join(", ", list.Select(toStringFunc))
yep what i do
Hmm so that would allocate only 1 string or what
toStringFunc would allocate at least N strings already though
no, that would generate a shit ton of garbage
concatenating each string creates a ton of intermediate strings
presumably, join would use a builder
for debugging stuff i really dont care about this stuff and += will re allocate a new string anyway
"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
So we are just back to this lol
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
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 +=
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
realistically it's not gonna matter if you aren't doing thousands or millions per frame
but for readability.. interpolation would generally be better than concatenation
any class or struct can implement its own ToString
This would call Vector3.ToString
Which has its own ToString implementation
If it didn't, it would just print out the type's name
public void saveData(data)
it says "identifier expected" on this line
but i have no idea whats causing the error
I think you have to specify what data's type is no?
oh, righttttt
It's interpreting data as the type of the parameter
but then it crashes into a ) instead of finding the name of the parameter
one more thing rq,
it says data is already an int, so no point in converting it into an int again
that's not how you turn a string into an int either
is it not toint and tostring
how is score.text defined?
it's ToString, but not ToInt
anything can be turned into a string
not everything can be turned into an int
what is the code now?
does it not occur to you to refer to the docs
the C# compiler does not appreciate when you make up random function names (:
you're really not giving much info to work with here
i try
You shouldn't be converting back from a string to an int at all
just save the score directly
so try convert string to int
the interface is there to display information. it's not part of your game logic
What is ToInt
i think they figured out it doesnt exist lol
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...
why do people always forget the cs 
So, you get the first log that properly displays an attack, and the log inside the function is printing null?
Yeah it actuallyy doesnt print null, its completely blank
First suggestion is to check to see if you have Collapse enabled in your console
It causes other issues in the game
Yeah, that's to be expected when using string interpolation
It doesn't actually use toString it casts
its not just in the console the entire projectile system dies
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
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
Yeah, that seems to be what's happening here
There's something else calling CreateProjectile that doesn't have a log before it
not possible
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
every single entity that makes an attack has this same set of messages in console, and only they can call the projectile manager function
Why not use a debugger to solve this easily?
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
It's what debuggers are for. No point struggling with random logs if it's easy to reproduce.
Yes... ill have to learn how to use debug. Its in VisualStudio or a Unity thing?
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
This will let you figure it out as you can inspect values and see the call stack when paused at a breakpoint
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?
Did you remember to wrap it in curly braces
why do you have if (a) if (b) c; anyways
do you have an else after that line or something
shorthand but I see that its not needed
This is key. Working on it now ty
shorthand for what?
if (a && b) is shorter 
yes
Use the debugger and you can step through and see what it's doing.
Do fix that if statement though
Ill def learn to use the debugger
this is the typical way yes
Physics collisions/queries are pretty much the only place where you sort of need to use TryGetComponent/GetComponent
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
That goes both ways, lots of beginners refuse help because it's not hand-holding enough.
: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
You can start by putting Debug.Logs everywhere you want to track the state of your game.
i asked him the same question and he told me to learn normal C#...
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.
Yes normal c# is the same used in Unity. So learning the basics would be applicable.
wait ill send it her
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
see above @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
you can copy the format from the bot embed
Surround code with three backquotes. Not quotation marks.
also, that's quite a large snippet, please use one of the paste sites. you don't need an account or anything.
alrght sorry for the inconvenience
A tool for sharing your source code with the world!
like this?
yes
alright finally
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
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
do i call it like i do in python by just typing the "insertname();"
alright thanks a lot, lots of love and have an amazing day
whats the best way to play a particle in code
call Play on the particle system?
Wdym by "the best way"?
there is only one way
Is luau somewhat similar to C#?
They are both imperative programming languages
that's about where the similarities end.
Thanks. Do you know how to code in C#?
How long did it take you to understand the basic things?
mm that's quite the loaded question
Not long at all because I already knew Java and other languages
about 5 seconds
one sec
Well how long did it take you to learn Java Basics?
Like 6 months?
that long huh, I'm disappointed in you
15 years ago ๐
(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 languagesof 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)
The PascalCase methods really threw me for a loop at the time
how can logic be only 'almost completely transferable'?
the 3 L's of programming
loop structure is somewhat different in functional languages
or so ive been told
i don't know any fully functional languages
Ah didn't learn Algol or Pascal first, gotcha
I was a Java baby
child
'Language is also shared quite a bit between languages'
gonna love to see that at work in asm or rpg
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
Just joshing you. Although I would guess you lost 99.9% of your intended audience with the use of the word paradigm
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?
please don't crosspost
i haven't edited it in forever, maybe it's due for an update
yeah, simple words of one syllable and put in lots of 'like's 'kinda's and 'thingies' and don't forget to misspell everything because, you know, spelling is not important
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?
default contact offset in physics 2d settings
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?
or offset them a little
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
No I mean to offset the sprite
What's the difference?
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
Just by moving the transforms
In the Unity editor
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 ๐
Yes put them on separate objects
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 ๐
Disable enter play mode domain reload in settings
Turn off debug mode if it's on
how to fetch all type of user defined object under UnityEngine.Object?or only UnityEngine.Object?
What's the end-goal?
You could find all derivatives of MonoBehaviour and ScriptableObject but that will include a lot more than "user defined" types
just want the type
For what purpose
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);
}
}
You could just check AssemblyCSharp for such types
but that will of course not include assembly definitions
didnt know about that assembly stuff
you already pinged me elsewhere what are you doing
https://i.gyazo.com/42c8da38e862c80b8f6062829295cb7c.png
Should I disable both or just domain/keep reload scene only?
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)
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
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
yes ctrl+R
Thanks
basically disabling reload domain is keeping the state of all variables from what I am reading
Yea everything is kept, you probably want scene reloading at a minimum so those instances are new.
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?
They do lots of different things.
I would say 5-10 seconds is pretty reasonable to wait
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
i have full reloading on and a typical play takes like 3-8 seconds but i have a good pc
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
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
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();
}
what was the expected way of turning class into readable string of variables
You mean... serialization?
I don't understand what you mean
i want turn my class into text file so somebody can fill this out and i re load it back into the game
You can use any serialization format you want
including json
yaml
a custom format
no it doesnt even have arrays
json has arrays
not mentioning dictionaries or nested classes
huh
You seem confused
maybe you're confusing Unity's JsonUtility with the json format
one of the json parsers doesnt support dictionaries, but there is another one that definitely supports them.
i think you are confusing unity's JsonUtility class with the entire concept of serializing to json. you can serialize to json using something like Json.NET which does support those things
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
No idea what you're talking about with loops
the serializer does everything
as long as you conform to its rules
yes it works
its build in
it's a package
well how will it serialize infinite class loop then
yeah newtonsoft one seem as effective as default one
it doesnt want touch my custom class list
show what you tried
ok it doesnt work on statics?
technically it can
it's just opt-in like for private members. the JsonProperty attribute should be enough for it
serializing a static member sounds very weird
yeah it doesn't make much sense
yeah it is very weird, but it is possible ๐คทโโ๏ธ
likely the design of the data model is off in the first place
yes
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
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
Yes... just make a container object
public class GameData { ... all the stuff ... }
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
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
[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
though i need go through everything slap jsonproperty on everything first
Your game logic can directly write to those classes as well(that's how I did it)
to not miss data
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?)
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
Reading through https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions
They mention: Use the expression-based string interpolation rather than positional string interpolation.
Then few lines below they use positional string interpolation:
public delegate void Del(string message);
public static void DelMethod(string str)
{
Console.WriteLine("DelMethod argument: {0}", str);
}
Any ideas why?
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
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?
who has time for that
That's technically the right thing to do, but trust me, nobody ever sticks with actually doing it
do you mean make variables private, not properties? because properties wouldn't make sense . . .
Especially if you know you'll definitely be accessing the class later on without a doubt
nope . . .
Oh wait ignore that lol
properties and fields (variables) are members of a class . . .
it's too late to be thinking ๐
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.
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
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
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
whats the reverse to [JsonProperty] to not include publics
Also JsonProperty is not needed by default
only if you use MemberSerialization.OptIn
If you use OptIn, then Ignore is not needed
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?
- Your Debug code is not drawing it at the correct place
- Something wrong with the layermask / layers of your objects
- There's no collider...
Lots of things could be wrong
you'd have to share details
this is the box colider of the surface the player is on:
You'd need to show the full object inspector so we can see the layer too
And then show the code for the raycast
and the layermask you're using, etc.
there is no layers as far as I know (I just set it to everything for test)
Show it
considering you're only drawing the line when there's a hit
clearly it's hitting
good point lol
right after it draws the ray cast, that is the only place in the code it sets isGrounded to true
What makes you think it's not working? Presumably you have an issue elsewhere in the code.
You'd have to show the rest of your code
That sounds like it always thinks there's a hit
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}!");
"The raycast hit FirstPersonController"
Its hitting the player?
this is why you need a layermask
dont forget that layer masks can be combined, so you dont lock yourself to one layer mask check
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 ๐
say what do you guys use to push unity onto github? because github desktop isnt detecting my changes for some reason
I use the git cli (command line interface)
but it sounds like you're probably just doing something wrong
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.
add a force in the direction of that object to all of the bodies
Thanks!
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?
There is a Dedicated #๐งฐโui-toolkit room, so you know
where i put jsonobject prefix so it stop erroring when trying deserialize
Ok, thanks.
Also sry
no worries ๐
json really doesnt like dictionaries i remembered that
json doesn't care about dictionaries
you are again thinking of JsonUtility in Unity
json itself basically is a dictionary
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.```
Ended up using the Context Menu 'trick' instead
Looks like your json doesn't match the type you are trying to deserialize into
by dont match you mean missing fields? because obviously i havent took ones i dont need
I mean the field type is wrong for the field it's trying to deserialize into
in the way it says in the error
that might fall better under #โ๏ธโeditor-extensions (i should have asked mine there too, i think)
Ooo ok, I'll delete my message here and copy it to there
i.e. your json has an object where an array is expected by the type you are deserializing into
well i basically have json of same object printed right before it
i just try to load it back and it errors out
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
errors on this
public Dictionary<string, bodypart> parts = new Dictionary<string, bodypart>();
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
only in the constructor, i dont use arrays anywhere else
hard to help without seeing the code and the data
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];
}
}
}```
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.
for every class?
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
but what about other classes that use parameter
i use constructors to pass data more compactly
Not a problem
Anyway as I mentioned this is the solution for your deserialization problem
ok from what i see i need change every class constructor
Nope
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
I never suggested removing them
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.
yeah remember when I said this
use it
as the error mentions
there is no data required to use it
because it should be a parameterless constructor
[JsonConstructor]
public MyClass() {}```
ah this
hey, I wasn't following the whole conversation, is this newtonsoft or jsonutil?
Given the links to the newtonsoft docs...
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!
You made a mistake in your !code formatting, please use a paste site when you're sharing this much code ๐
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
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
For the animation states that you want to "freeze", control their time or speed with a parameter instead of animator.speed (which affects everything).
I tried something like that but that made it worse
You did it wrong
Check if you have errors
Also make sure your build does not rely on editor namespace features. Those are stripped out in builds
Where can I see build errors?
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 ๐
Preferably implement a console where these things are delegated to. There are plenty of console packages you can find online
Also just making a general window and hooking on Application.logMessageReceived or Application.logMessageReceivedThreaded allows you to view errors
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
Cursor behaviour is very different between the two. In the editor you can very easily unhook the cursor so that it doesn't get stuck by accident. You might have to implement your system differently to account for that
Generally implementing cursor specific behaviour is best done by testing it in actual builds since that's how it ends up as
I use this Cursor.lockState = CursorLockMode.Locked; but I guess it does not work in builds?
nvm all good now ๐
Here's a video to showcase the issue better.
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
Seems like a gimbal lock issue because euler angles
What is the point of cs transform.eulerAngles = new(ea.x, transform.eulerAngles.y, ea.z);
?
How does it act if you remove that part?
I was suspecting that too, and also what gpt suggested.
What can I do about it tho?
let me try that
I was doing that thing in the first place because I want my other axes to be left untouched
that sadly didn't fix it either way :/
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)
I am making a specific kind of movement and rb is supposed to rotate the weapon on the x axis only(flip it p much)
transform is for looking around, shouldn't affect the rb in any way
What object is this script attached to
object that's got the rigidbody and a collider, and is also a parent of the model
Of course transform will affect the rigidbody then
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.
Also, ehre's the vid showcasing what happens without the >=180 fix and the euler stuff you recommended:
https://www.youtube.com/watch?v=AlfOnFPuwXQ
once the object goes past a certain point(180deg X I assume), the rotation just flips
Video is private
Use rigidbody methods/properties to move and rotate it but you can update the camera's rotation separately
Issue is, I am not rotating the camera here, I want to rotate the blade(which uses rb) :/
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?
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)
I see, this is quite weird tbh.
I'll try the rb approach and see if that feels bad.
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
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 )
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 ?
https://docs.unity3d.com/Packages/com.unity.splines@2.4/manual/animate-movement.html
This also just kinda explained some of the settings but not exactly what im looking
is it better to use broadcast message or actions for bullets hitting things
actions
how do i set that up cause my enemy needs a refrence to the bullet script no?
and they get instantiated
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>())
surely u have to bind the actions to the desired function onenable
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
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
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
so on the bullet script OnColliderEnter invoke the action then on the enemy script OnColliderEnter bind the action is there not a possibility for like a race condition
thank you for the advice and I did implement it and the movement now works but now the animation freezes even when the z key is released and it stays in the run blend tree without switching to the walk one and the freezing animations are now also staying for longer like one state is being repeated for 3 keys or so
If the enemy script needs to do anything because of the bullet, then the bullet calls that method.
bullet hits enemy -> var enemy = getcomponent<enemy>() -> bullet calls enemy.DoDamage(int)
that seems bad tho what if i need to do damge to debris or a vehicle surely i have to use actions here or broadcast message
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
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
Depends if you want to rotate in local or world space ๐
I have a camera that I need to manipulate its local rotation to look at a target. Thats the case I had in mind when writing that ๐
If you want to look at a target, just "LookAt" it or use the direction from position subtraction. I do not see any need to use local vs world, when you just want to look at the position of an object
My camera is a child object though.
and your parent is moving and rotating?
Yes
I move my playerObject and Camera object seperately.
While slerping the rotations
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?
No its a first person controller.
I rotate my player object on world position while doing my camera on local
so you could just move your player to look the direction and your camera just be a stationary child?
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
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.
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
It depends on which space should be "fixed"
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
I see. On your point, you're using its world position right?
So you can rotate an object on axis, its parent is not being rotated. If you start rotating like parent and child y axis, things can start to freak out ๐ But if the target is above the player for example, your camera can still look up, while your player only looks in the direction projected on a plane without upwards rotation
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
Ah okay so transforming is necessary
Yeah thats pretty much it. Its all new to me so I am having trouble explaining myself
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
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
Hm makes sense. Could unity be handling those in some cases?
Converting local and world rotations operations I meant
I don't know what that would entail
Not sure what oyu mean either? Unity does, what you tell it too. If you rotate the parent, it will rotate it and (under the hood probably) calculate the world positions of the children etc etc. But you have to tell unity, HOW to rotate.
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.
you can always get the world rotation and transformdirection to local space and so on. Just play around too, helps sometimes, to just see what you are changing ๐
Yeah I will definitely keep doing that. Thanks!
if i have 2 static constructors which one runs first
How can you have 2 static constructors?
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.
According to the docs:
The user has no control on when the static constructor is executed in the program.
So it's basically random
what docs are you looking at?
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
we're looking at the same page
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
not true, the static constructor is executed when the first call is made to the class
I see, that's a weird statement they make then
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
is there away to increase the time before a rigidbody falls asleep after not being used
Presumably the C# programmer
Yep there's a property for it
Check the docs
Well it's not based on time actually
It's based on "energy"
where is this sorry i cant find it
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?
well, from my experience with making a flappy bird game in Unreal, it doesn't!
You can Also just set it to never sleep
Lol
but thats very taxing no?
Yeah, I always assumed it would have a time threshold of some sort
birds do that irl, it's normal
if you have hundreds of these rigidbodies, sure
Depends on how many things you do it with
oh no just for the player
go nuts
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.
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
@wintry quarry Hmm.. https://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/guide/Manual/RigidBodyDynamics.html#sleeping
When an actor does not move for a period of time, it is assumed that it will not move in the future either until some external force acts on it that throws it out of equilibrium.
An actor goes to sleep when its kinetic energy is below a given threshold for a certain time.
At least in PhysX it has a timer
note that you can explicit tell a rigidbody to wake up
it doesn't look like you can check if it is asleep, though
yes, but you have to explicitly do that, you cannot just poke it
lazy bloody rigidbodies, I bet they are all Gen Z or millennials
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
pls help someone here is my new script https://paste.ofcode.org/Ftdf37bDpS8fGPqRz2VNDZ
!Code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
A tool for sharing your source code with the world!
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
i followed the CodeMonkey tutorial... tbh im bad at coding im trying to learn
but i will try removing some stuff
pls help someone here is my new script https://paste.ofcode.org/Ftdf37bDpS8fGPqRz2VNDZ
What is the purpose of your raycast ? Checking if the object is on ground ?
no, checking if its hitting an object, trying to make it work like RigidBody but in the tutorial he decided to use Raycast
OK. And the issue is the raycast always hit something ?
Yeah makes sense - It doesn't seem like the time is configurable though
I might be wrong here, but you might need to make your raycast ignore your object. I suppose you have your player character from which the raycast start and your issue might be that it detects your player collider.
In your raycast call, you can add a LayerMask (https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.Raycast.html) so that it doesn't interact with those layers. Then assign the ignored layer to your player
i dont think thats the problem, because it worked before changing it to this Raycast type, at first it was just Raycast now its CapsuleCast... also what is a layer mask.. the Docs seem to go a lot deeper
To answer to what a layer mask is https://docs.unity3d.com/6000.0/Documentation/Manual/layermask-introduction.html
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...
2:11h of the video
at 2:11:14 exactly
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 ?
i cant remember why, i tried reverting it to .7 again... didnt work
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 ?
what capsule? and ye i have same player and empty gameObject
i didnt use a capsule
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
i dont have it
the button component can't have Vector2, no
what should i do?
Only bool, string... and.. something else int maybe
make a string and break it down with regex?
public Vector2 WhatDo;
public void ChangeComponentOrDisableComponent() {
DoSomething(WhatDo);
}```
I don't know the best solution in your case. I don't use these
There you go, Prae has given you the way
hmm i think i got an idea of how i could do that, thanks
@wintry quarry can u help me with that
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
ye, then its editor thing?
start debugging your code
Probably. Sorry I can't help much, but I don't have any more explanation for the moment
wdym?
first thing you need to do is check which object your cast is hitting
tbh im trying to find out
debugging is the process of analyzing and investigating your code and how it runs to fix bugs
Through... crystal balls? Summoning demons?
Use Debug.Log and print it.
ohhh
Debug.Log(What?)
what object should i write for asking the game what Raycast is hitting
Raycast stores that info in RaycastHit
ok ty
well you need to switch to a form of CapsuleCast that actually uses a RaycastHit out variable
right now you don't have one at all
then what do i write there to debug it??
The collider would be a good start
dont understand whats after the first if statement...
should i just copy that there?
the innermost if statement in there is not necessary
ye
Look at the docs
Look for the version with the out Raycast parameter
use that one
i read it all, didnt understand most of it. idk what to do now, im more confused
what part is confusing you
all of it
that's not helpful
sry ;-; i just want to know what is hitting it . . .
I'm explaining how to do that to you
There's even a code example on the page
that has the RaycastHit param
i tried reading all of it, i didnt understand it... i will reboot system and come back
the relevant part is the one where you use the signature that supports the out parameter with RaycastHit
You should be able to access that raycast hit and its properties, store it like you would any other var
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);
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?
you can ignore the last 2 parameters as they are optionals (they have an = sign)
no
poo
You can think of a class as a "blueprint" for a type of object
oh ok
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
ohhh i see that makes sense
From that, you can create any number of instances of the class, which would be objects that behave as your class describes
oh i see thank you so much
now its even more confusing than before... what are there Mathf.Infinity and QueryTrigger... i dont understand anything now
thats the signature, its just an example
they are given the defalt values
so, let me try to open the VSCode and see what should i do ...
ideally your IDE shows you the signature based on the order of your parameters
OR you can use myparam: thevalue and you can order them how you please
how would i do an if something and something? the code doesnt seem to know what "and" is
&&
c# doesn't write AND
also easily googleable.
oh, thanks
u mean the thing where it shows which does what? like which format of code does what?
the signature of the method you are writing
oh i meant that ye
(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?
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'll send it in that, thanks!
like this?
also how do i make an else
i just added out RaycastHitOutput hitinfo in the last part
hitInfo contains data. You should be able to type hitInfo.Collider if i'm not mistaken
also for some reason && is invalid expression tern
ok, is that all?
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?
A tool for sharing your source code with the world!
oh, && cannot be applied to operands of type cursorlockmode and bool?
show what you're trying to do
cursorlockmode is an enum
it can only be used in if statement if you are comparing
screen is small, it wont even show whats after it. i will try reducing font size
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;
}
like what should i do ??
(Crusor.Lockstate == myState && something else)
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...
basically i want if you press esc the cursor unlocks and when you press esc again the cursor locks
are you seeing things popup when you access the . on the hitinfo?
I see stuff like OnCollisionEnter
cant see Collision or collision
hitInfo doesnt have OnCollision enter
let me show.. give a min
like a toggle ?
basically what you see in most games(so you can access settings n such when you pause)
yea
why not just a bool
isPaused = !isPaused
Cursor.LockState = isPaused ? cursor.lockstate = unlocked : locked
so i create a bool
ye? isnt that supposed to be a name
no?
ok sry, i will try reading signature thing again
is that was written on the docs?
what docs... i couldnt understand any of it
the one that Praetor sent you
i will try reading it again . . .
if (Cursor.lockState = isPaused)
this gave an error
because its nonsense
you're assigning a bool to a enum
not even remotely close to the example i wrote
i made a public bool isPaused
and?
== is for comparison
= is for assignment
hows that have to do with what I said @warm field
read the code again #๐ปโcode-beginner message
if you're confused on the ? just ask
look here at the type
just a hint - its about assigning an enum value based on bool state by ternary operator, not about assigning bool to an enum
maybe a should've just used an IF else statement as example
yea im confused on how the ?: works
so its a WHOLE thing? like a variable?
its just a fancy shmancy if else statement in one line
Confusing example
clearly
? is question, and : is choice?
correct
I mean what is the cursor.lockstate = unlocked part
yeah but I showed them early that lockstate wants an enum for lockstate but idk if they paid attention, assumed they knew I meant thats the part with enum, ig not
so if does Cursor.lockState = isPaused? Cursor.lockState = unlocked : Locked
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?
A tool for sharing your source code with the world!
this this syntax does not make sense. the conditional operator works like this:
condition ? trueResult : falseResult;
no, put both lockstates > I showed you wass example variables you replace yours with
didn't feel like typing the enum 3 times
It evaluates to either trueResult or falseResult
i still dont understand
The second you add an if statement where?
Show the new code you would be adding and where you would be adding it.
whats not to understand? fix your typo lol
i tried adding the RaycastHit hit
okay ? so now put it in the method
you literaly have it correct almost, just wrong type
If you wanna switch between locked and none, jsut
Cursor.lockState = (CursorLockMode)(trueOrFalse + 1);
Expected responses ๐
read your code
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);
startPanel.SetActive(true);
currentState = MenuState.CreditOption;
}
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);```
i got this:
if (Cursor.lockState = isPaused ? Cursor.lockState = isPaused : Cursor.lockState = !isPaused)
why though ?
you dont need that much nesting
well, no, it's not
isPaused is not a valid value for the CursorLockMode enum
since I presume that's a boolean
I see = not ==
isPaused is a bool
i still dont know what to do... wdym put it in the method
Lowk need help real quick
Again = is assignment and == is comparison
doing if (x = y) makes no sense
it would be if (x == y)
Ooohhh...
It all happens at the same time... I must have been drunk coding this๐ญ
In the method. Like this. how you wrote it like this. just fix the type
you see its red?
YOu should use else if and/or use a switch to handle the different states
i did, it gave more errors
This half arsed example started this whole confusion
it will try to assign y into x, then interpret y as a boolean, since the = operator returns the assigned value
i switched RaycastHitOutput with hit
Thank you!
its saying == cannot be applied to operands of type cursorlockmode and bool
indeed, because that comparison makes no sense
yes, because you can't compare a CursorLockMode and a bool.
don't see how its half assed but okay lol
now its this:
if (Cursor.lockState == isPaused ? isPaused : !isPaused)
you have cursor.lockstate stuffed in the middle there
I suggest go through this tutorial and all on !learn ... you are missing very basic knowledge on what terms you are fighting with in coding
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
instead of randomly making changes until it compiles, you need to stop and think about what these operators actually mean
What is the objective here?
whatever lol OP just needs basic c#
What are you trying to make your game do?
toggle unlock/lock cursor
that is probably the 500th time this has been suggested to him
ohhh well, good to know, will take note ๐
im still stuck on 1 point, what do i do after making it hit instead of RaycastHitOutPut
Okay, so you need to flip the value of your isPaused variable, then pick the correct cursor lock mode based on its new value.
wdym making hit instead ? the name of the variable is not relevant .. Its the type you have miswritten there
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.
only thing i found so far is movement script
i still dont understand anything... what should i type to fix it
literally not worth helping because he refuses to help himself
i just realised "junior programmer" pathway exists bruhhh
You have two identifiers:
- The type of the variable
- The name of the variable
You used the wrong identifier for the type of the variable.
I told you man, you gotta write RaycastHit, if you dont "understand anything" you need to take a step back and learn the basics, I'm not finna try explain how a method is written, sorry .
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
but i wrote RaycastHit
Okay, so what is the problem?
idk
show us you did that
i changed it to the hit thing in the variable RaycastHit
That sentence is incoherent.
"the hit thing" do you realize Idk what that is? I'm not telepathic
we can't se what you did and didn't do unless you show it..
i will show
literally just needed to take oue OutPut idk why you made it so complicated lol
we all used to be like this once but damn
pro tip: don't write extra things that dont exist.
That is not what you were told to do.
You were told to use the correct type name, RaycastHit
i did type RaycastHit
You originally wrote RaycastHitOutPut. This is not the name of a type that exists.
I wonder what those red lines are below your code parts ... ๐
In what universe is rayhit the same as RaycastHit?
yes but now you put it at a different spot..
so now you're passing the variable wrong
oh my this is insane
its a thin path between entertaining and frustrating
so i should put RaycastHit just that instead of Rayhit